Spaces:
Paused
Paused
fix: absorb autoteam-1 auth and CPA quota parity
Browse filesFiles changed (12)
- .trellis/spec/backend/account-disable-cpa-sync.mdAdded+290
- .trellis/spec/backend/index.md+2-1
- .trellis/tasks/05-19-autoteam1-full-parity-completion-audit/prd.mdAdded+178
- .trellis/tasks/05-19-autoteam1-full-parity-completion-audit/research/autoteam1-full-parity-matrix.mdAdded+624
- src/autoteam/accounts.py+38-1
- src/autoteam/codex_auth.py+1132-146
- src/autoteam/cpa_sync.py+31-1
- src/autoteam/mail/__init__.py+34
- src/autoteam/manager.py+767-70
- tests/unit/test_cpa_sync.py+110
- tests/unit/test_free_registration_hardening.py+154
- tests/unit/test_round10_master_codex_session.py+78
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290# Account Disable and CPA Sync Contract
## Scenario: local account disable controls
### 1. Scope / Trigger
- Trigger: an operator needs to keep an account record and auth file locally while excluding that account from automated checks, rotation, reuse, and CPA publication.- Applies to: `src/autoteam/accounts.py`, `src/autoteam/api.py`, `src/autoteam/cpa_sync.py`, and Dashboard account operations.
### 2. Signatures
- Account row field: `disabled: bool`.- Helper: `is_account_disabled(acc: dict | None) -> bool`.- API: - `POST /api/accounts/{email}/disable` - `POST /api/accounts/{email}/enable` - `POST /api/accounts/bulk/disable` with body `{ "emails": string[] }` - `POST /api/accounts/bulk/enable` with body `{ "emails": string[] }`- Status response account fields: - `status`: display status, `disabled` for disabled non-main accounts. - `raw_status`: persisted lifecycle status such as `active`, `standby`, or `personal`.
### 3. Contracts
- `load_accounts()` and `save_accounts()` must normalize legacy rows so missing `disabled` becomes `false`.- Main account rows must not be disabled or enabled through these endpoints.- Disabled non-main accounts remain visible in `/api/status`, but quota probing must skip them.- Disabled rows must be excluded from `get_active_accounts()` and `get_standby_accounts()`.- Auto-check and rotation candidate selection must treat disabled rows as unavailable.- `sync_to_cpa()` must not upload disabled accounts.- A disabled account's local auth file is still protected from accidental CPA remote deletion by the existing same-file delete guard.
### 4. Validation & Error Matrix
| Condition | Required behavior || --- | --- || Empty or invalid email | `400` with a business message || Main account email | `400`, never mutate `disabled` || Unknown email | `404` for single toggle; `missing_emails` entry for bulk || Already target state | No mutation; include in `unchanged_emails` for bulk || Mixed bulk payload | Deduplicate, skip main, report missing, mutate valid rows || Disabled row in status | Return `status="disabled"` and preserve `raw_status` |
### 5. Good/Base/Bad Cases
- Good: disabling an `active` account keeps the row and auth file, hides it from quota checks, and surfaces `raw_status="active"` plus `status="disabled"`.- Base: enabling a disabled standby account restores `status="standby"` in the display status.- Bad: deleting or moving auth files when an account is merely disabled.
### 6. Tests Required
- `tests/unit/test_accounts.py` - Normalizes missing `disabled`. - Excludes disabled active/standby rows from active/reuse helpers.- `tests/unit/test_api_status.py` - Single disable/enable. - Bulk disable/enable with missing, unchanged, duplicate, and main-account rows. - `/api/status` skips disabled quota checks and counts disabled rows.- `tests/unit/test_cpa_sync.py` - Disabled account is skipped for CPA upload. - Matching remote auth file is retained by delete guard.
### 7. Wrong vs Correct
#### Wrong
```pythonactive = [a for a in load_accounts() if a["status"] == STATUS_ACTIVE]```
This lets a locally disabled account re-enter auto-check, rotation, or CPA sync.
#### Correct
```pythonactive = [ a for a in load_accounts() if a["status"] == STATUS_ACTIVE and not is_account_disabled(a)]```
## Scenario: CPA list failure handling
### 1. Scope / Trigger
- Trigger: CPA may be unreachable, return a 5xx page, return non-JSON, or return a malformed JSON shape.- Applies to `list_cpa_files()` and all call sites that depend on CPA truth.
### 2. Signatures
- `list_cpa_files() -> list[dict]`.- Raises `RuntimeError` on request, HTTP, JSON, or schema failure.
### 3. Contracts
- Do not convert CPA failure into `[]`.- Do not treat remote failure as "remote has no files".- Callers performing sync or cleanup should fail loudly or surface the error rather than deleting based on false emptiness.
### 4. Validation & Error Matrix
| Condition | Required behavior || --- | --- || `requests.get` raises | `RuntimeError("[CPA] auth-files list request failed: ...")` || HTTP status is not `200` | `RuntimeError("[CPA] auth-files list failed: HTTP ...")` || Body is non-JSON | `RuntimeError("[CPA] auth-files list returned non-JSON response")` || JSON `files` is missing or not a list | `RuntimeError("[CPA] auth-files list response missing files list")` |
### 5. Good/Base/Bad Cases
- Good: CPA returns `{"files": [...]}` and the sync proceeds.- Base: CPA has zero files and explicitly returns `{"files": []}`.- Bad: CPA returns a `503` HTML page and the app interprets that as an empty CPA file set.
### 6. Tests Required
- `tests/unit/test_cpa_sync.py::test_list_cpa_files_raises_on_non_200`.- `tests/unit/test_cpa_sync.py::test_list_cpa_files_raises_on_non_json`.
### 7. Wrong vs Correct
#### Wrong
```pythonif resp.status_code != 200: return []```
#### Correct
```pythonif resp.status_code != 200: raise RuntimeError(f"[CPA] auth-files list failed: HTTP {resp.status_code}")```
## Scenario: Managed-account deletion and Team state parsing
### 1. Scope / Trigger
- Trigger: deleting a locally managed account, rendering `/api/team/members`, or reconciling local rows against ChatGPT Team member/invite responses.- Applies to `src/autoteam/account_ops.py`, `src/autoteam/api.py`, and any caller that consumes `fetch_team_state()`.- Goal: tolerate known ChatGPT Team API response-shape drift without deleting protected local credentials or mutating the wrong remote target.
### 2. Signatures
- `fetch_team_state(chatgpt_api) -> tuple[list, list]`.- `extract_team_members(payload) -> list`.- `extract_team_invites(payload) -> list`.- `team_member_email(member) -> str`.- `team_member_user_id(member) -> str | None`.- `team_member_role(member) -> str | None`.- `team_invite_email(invite) -> str`.- `delete_team_invite(chatgpt_api, account_id: str, invite: dict | None = None, *, invite_id=None, email: str | None = None) -> dict`.- `delete_managed_account(email, *, remove_remote=True, remove_cloudmail=True, sync_cpa_after=True, chatgpt_api=None, mail_client=None, remote_state=None) -> dict`.- `GET /api/team/members` response rows must contain `email`, `role`, `user_id`, `is_local`, and `type`.
### 3. Contracts
- Team member responses may be a list or a dict containing `items`, `users`, `members`, or `account_users`.- Team invite responses may be a list or a dict containing `items`, `invites`, or `account_invites`.- Member identity fields may live at the top level, under `user`, or under `account_user`.- Invite email fields may live at the top level, under `user`, or under `account_user`.- Team API `401` / `403` and HTML/non-JSON responses must raise a readable `RuntimeError` that tells the operator to redo administrator login.- Invite cancellation must first try `DELETE /backend-api/accounts/{account_id}/invites/{invite_id}` when an id exists, then fall back to collection delete with `{"email_address": email}`.- Deleting an account must call `delete_account_from_configured_targets(..., include_disabled=True)` so CPA and Sub2API cleanup use the shared configured-target router.- Local auth paths may be stored as absolute paths, `/app/...` container paths, `data/auths/...`, or `auths/...`; deletion must resolve known candidates without string-only assumptions.- Non-main local credential seats with an auth file and no mail binding are protected from destructive deletion; the cleanup result must expose `protected_local_credential=true`.- Mail-provider deletion must prefer `mail_account_id` and fall back to legacy `cloudmail_account_id`.
### 4. Validation & Error Matrix
| Condition | Required behavior || --- | --- || Team users/invites return known list-wrapper shapes | Return extracted records without dropping nested identity fields || Team users endpoint returns HTML/login/challenge page | Raise `RuntimeError` containing `接口返回了非 JSON 内容` and redo-login guidance || Team users endpoint returns `401` or `403` | Raise `RuntimeError` containing redo-login guidance || Invite-id delete returns non-success and email is known | Retry collection delete with `email_address` || Account auth file uses a container `/app/...` path | Resolve the corresponding project-local candidate before deletion || Account has local auth and no mail binding | Return cleanup with `protected_local_credential=true`; do not delete local row, auth file, CPA, or Sub2API || Account has `mail_account_id` | Delete that provider account id, even when `cloudmail_account_id` is missing || Configured target cleanup returns CPA/Sub2API deletions | Surface them as `cleanup["cpa_files"]` and `cleanup["sub2api_accounts"]` |
### 5. Good/Base/Bad Cases
- Good: `/api/team/members` receives `{"items": [{"user": {"email": "...", "id": "...", "account_role": "admin"}}]}` and returns normalized row fields for the frontend.- Good: deleting a provider-backed account removes the Team member/invite, local auth file, local row, configured remote targets, and provider mailbox id once.- Base: a personal or auth-invalid row still skips Team remote fetch, but local and configured-target cleanup remains available.- Bad: assuming `member["email"]` and `member["user_id"]` are always top-level fields; this silently hides nested Team rows from cleanup and UI.- Bad: calling CPA-only cleanup directly from `delete_managed_account()`; this bypasses Sub2API and configured-target availability rules.- Bad: deleting a manually imported credential row simply because it has an auth file but no provider mailbox binding.
### 6. Tests Required
- `tests/unit/test_account_ops.py` - `fetch_team_state()` parses member/invite wrapper variants and nested identity fields. - Team API HTML/auth failures raise readable redo-login errors. - `delete_team_invite()` falls back from invite-id delete to collection delete. - `delete_managed_account()` uses `mail_account_id`, configured-target deletion, and local credential protection. - `/api/team/members` renders normalized nested Team rows and still stops `ChatGPTTeamAPI`.- Regression suites: - `tests/unit/test_round6_patches.py` - `tests/unit/test_spec2_lifecycle.py` - `tests/unit/test_cpa_sync.py` - `tests/unit/test_sub2api_sync.py`
### 7. Wrong vs Correct
#### Wrong
```pythonemail = (member.get("email") or "").lower()user_id = member.get("user_id") or member.get("id")```
This misses nested `user` / `account_user` shapes and can leave real Team seats undeleted.
#### Correct
```pythonemail = team_member_email(member)user_id = team_member_user_id(member)```
Use the shared shape helpers wherever Team state is parsed, including cleanup and `/api/team/members`.
## Scenario: active CPA publish preflight
### 1. Scope / Trigger
- Trigger: `sync_to_cpa()` is about to publish a local `STATUS_ACTIVE` auth file or decide whether an existing CPA copy should be deleted.- Applies to `src/autoteam/cpa_sync.py` and the unit tests that cover active credential publish branches.- Goal: make publish/delete decisions from live quota truth, not from the local status string alone.
### 2. Signatures
- `_active_auth_publish_decision(acc: dict, path: Path) -> str`- `sync_to_cpa() -> dict`- `check_codex_quota(access_token, timeout=8) -> tuple[str, dict | None]`
### 3. Contracts
- `quota_status == "ok"` means the active credential may be published.- `quota_status == "network_error"` means the remote copy stays in place and the local row waits for a later round.- Any other non-`ok` quota status means the existing remote copy should follow the delete path used for stale active files.- A successful live `ok` check may refresh the local auth bundle's `proxy_url` before upload.- `sync_to_cpa()` should surface active-publish counters so operators can see why a file was uploaded, kept, or deleted.
### 4. Validation & Error Matrix
| Condition | Required behavior || --- | --- || Active quota check returns `ok` | Upload the local auth file and refresh proxy metadata when available || Active quota check returns `network_error` | Keep the remote copy and do not delete or upload that file || Active quota check returns `exhausted` or another terminal failure | Delete the remote copy through the existing delete path || Active quota probe raises | Log the failure and keep the remote copy for the next round |
### 5. Good/Base/Bad Cases
- Good: a live `ok` credential is republished with fresh proxy metadata.- Base: a transient network error leaves the remote CPA copy untouched.- Bad: deleting or uploading active CPA files purely because the local row still says `active`.
### 6. Tests Required
- `tests/unit/test_cpa_sync.py::test_sync_to_cpa_skips_exhausted_active_credential_before_upload`- `tests/unit/test_cpa_sync.py::test_sync_to_cpa_keeps_remote_on_active_quota_network_error`- `tests/unit/test_cpa_sync.py::test_sync_to_cpa_refreshes_proxy_url_before_upload`
### 7. Wrong vs Correct
#### Wrong
```pythonif acc.get("status") == STATUS_ACTIVE: upload_to_cpa(path)```
#### Correct
```pythonquota_status, _info = check_codex_quota(access_token, timeout=8)if quota_status == "ok": upload_to_cpa(path)elif quota_status == "network_error": keep_remote_copy()else: delete_from_cpa(path.name)```
Live quota must decide the publish branch before the remote copy is touched.20 unmodified lines21222324242526272820 unmodified lines| [Logging Guidelines](./logging-guidelines.md) | Structured logging, log levels | To fill || [Runtime and Docker Hardening](./runtime-docker-hardening.md) | Docker resource bounds, Playwright cleanup, resource probes, transport safety, and IPv6 proxy isolation | Active || [Free Registration Hardening](./free-registration-hardening.md) | Fill-personal safety boundaries, Team-seat preflight, and SignupProfile consistency | Active || [Account Disable and CPA Sync Contract](./account-disable-cpa-sync.md) | Disabled-account automation exclusion and explicit CPA list failure handling | Active || [Account Disable and CPA Sync Contract](./account-disable-cpa-sync.md) | Disabled-account automation exclusion, active CPA publish preflight, and explicit CPA list failure handling | Active || [Setup Diagnostics Contracts](./setup-diagnostics.md) | Setup-stage read-only diagnostics such as DNS checks and auth/rate-limit behavior | Active |
---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178# autoteam-1 full parity completion audit
## Goal
Continue the long-running objective: absorb the good, proven ideas from`D:\Desktop\autoteam-1\AutoTeam` into the current project at `D:\Desktop\AutoTeam`.
This task is not a blanket copy. The two repositories have diverged and the currentproject already contains stronger local work in several areas. The work here is toturn "all good points" into a concrete, evidence-backed checklist, identify theremaining gaps, and then implement the next safe migration slice without disturbingunrelated active work.
## Current Baseline
Recent current-repo commits already landed the largest seat-rotation slice:
* `05bf6da fix: harden seat rotation and direct signup race`* `d8f55d5 chore(task): archive 05-19-autoteam1-seat-rotation-hardening-migration`* `efad4b5 chore: record journal`
That prior slice covered `ROTATE_SKIP_REUSE`, remove-before-create replacement,managed child validation, direct signup race wiring, multi-master direct parallelpropagation, auto-check cooldown/blocker handling, backend specs, and unit tests.
## Requirements
* Build a prompt-to-artifact checklist for the global objective, not just the last rotation task.* Compare target-repo recent commits and target-only files against current code, tests, specs, and UI artifacts.* Classify each target capability as: * absorbed with evidence, * partially absorbed and needing deeper audit, * not absorbed and worth migrating, * not worth migrating because current repo has a better/incompatible pattern.* Preserve current repo advantages: multi-provider mail fallback, account-state machine, multi-master workspace pool, cleaner frontend design direction, CPA delete guard, and the 3-seat Team cap.* Do not copy target files wholesale. Migrations must be adapted to current module boundaries and tested with current tests.* Do not use `/api/sync` as a smoke test and do not restart live Docker during audit-only work.* Do not include unrelated existing dirty files in commits.
## Acceptance Criteria
* [x] Research file contains a target-commit-to-current-evidence matrix for recent target commits.* [x] Research file lists target-only source/UI/test files and states whether they are equivalent, superseded, or candidates for migration.* [x] At least one concrete next implementation slice is selected, with explicit in-scope and out-of-scope boundaries.* [x] If implementation is started, related tests are added or updated and `ruff` plus relevant `pytest` are run.* [x] If no implementation is appropriate after audit, the audit explains why the global objective is still not complete or what evidence is needed before marking it complete.
## Initial Findings
See `research/autoteam1-full-parity-matrix.md`.
## Implemented Slices
* P1: Added a current-repo regression test for target-2 exhausted blocker removal with a stale remote overcount. The adapted current behavior remains remove-before-create rather than target-style preswitch.* P2: Added read-only DNS diagnostics via `src/autoteam/dns_diagnostics.py` and `POST /api/setup/dns/check`. Mutating Cloudflare DNS upsert remains out of scope.* P3: Migrated target `account_ops` Team-state parsing and deletion safeguards into current repo boundaries: nested Team member/invite helpers, readable auth/HTML failures, invite-delete fallback, configured CPA/Sub2API target cleanup, generic mail account deletion, local credential seat protection, and `/api/team/members` normalized rendering.* P4: Migrated target `8f17448` CPA credential gate into current auto-check shape: read-only CLIProxyAPI provider-auth metadata can trigger the existing `auto-fill` path when Team is full, local active children are below target, and CPA has zero usable provider credentials. Management failure is not treated as zero.* P5: Migrated reset-quota local recovery: `cmd_reset_quota_recovery`, CLI `reset-quota`, `POST /api/tasks/reset-quota`, and tests recover stale exhausted rows without touching Team, CPA, or Sub2API.* P6: Migrated main-Codex after-admin improvements in current repo shape: local-only `MainCodexLoginFlow`, action-aware main-Codex status, `POST /api/main-codex/login`, sync-target preflight for `POST /api/main-codex/start`, and explicit remote deletion routes through `sync_targets.py`.* P7: Migrated the safe auth-path subset from target auth-repair work: manager-level auth file resolution now handles host-absolute, `/app/...` container paths, project-relative `data/auths/...` / `auths/...`, and bare filenames across the current repo's auth search dirs. Team reconciliation now protects standby/auth-pending rows when a real local auth file exists and restores recovered Team auth rows with `protect_team_seat=True`.* P8: Migrated target OAuth/auth-repair diagnostic labels and same-round delay helper for transient organization/region pages such as `oauth_timeout`, `unsupported_region`, `account_selection`, and `no_valid_organizations`.* P9: Migrated target workspace-selection hardening in current repo shape: `chatgpt_api` now filters workspace candidate noise, waits for post-selection ChatGPT readiness, and shortcuts completed ChatGPT home states; `codex_auth` exposes compatibility wrappers to the existing shared `oauth_workspace.py` detectors/selectors.* P11: Migrated the safe lightweight Codex OAuth helper subset from target `test_signup_flow_profiles.py`: API organization dropdown selection, account chooser selection, OAuth trace filtering/classification, timeout and `no_valid_organizations` retry-page recovery, login-challenge completion, OTP rejection cache hashing, and OTP submit acceptance of OAuth progress URLs.* P12: Migrated split verification-code handling for direct and invite registration: delayed single-character input detection, single-input fallback, structured invite diagnostics, and shared submit helpers that wait for the registration step to advance.* P13: Migrated the safe session fallback subset for Codex auth: `_fetch_team_session_bundle_from_context`, explicit `pre_signed_in_cookies`, and opt-in `return_result=True` wrapping. The default `login_codex_via_browser()` contract still returns the existing bundle/`None` shape.* P14: Migrated the safe `_login_codex_with_result` subset from target auth-repair work. The helper normalizes explicit `return_result=True`, legacy bundle/`None`, retryable failures, and non-Team bundles into one result shape, while keeping it isolated from `cmd_check` and Team-seat release policy.* P15: Migrated the safe `cmd_check` auth-repair entry subset from target: `force_auth_repair`, `preserve_low_active`, historical-low-quota handling when live quota returns `network_error`, auth-pending scanning, and per-account mail provider routing. This keeps the current persisted `auth_invalid` alias and does not change `_record_auth_repair_failure` release policy.* P16: Migrated the low-risk `_record_auth_repair_failure` policy subset: repeated `email_verification` can release a Team blocker after retry budget is exhausted, missing-auth `login_state_lost` releases and retires the unusable row, released repair failures are marked disabled/reuse-disabled to avoid accidental standby reuse, and protected local credential seats are paused without release.* P17: Migrated the Cloudflare temp-email compatibility facade and metadata extraction improvement: `autoteam.cloudflare_temp_email` remains a legacy import path, `normalize_cloudflare_temp_email_base_url()` strips `/admin`, `MailProvider` extract helpers prefer `metadata.ai_extract` before subject/body parsing, and target-style `test_cloudflare_temp_email.py` now passes against current repo.* P18: Migrated the same real-time quota principle into CPA publish routing: `sync_to_cpa()` now re-checks active auths immediately before upload, keeps the remote copy on `network_error`, publishes only when `check_codex_quota()` returns `ok`, and deletes remote active files on exhausted/terminal failures. Tests cover the live keep-remote and delete-remote branches plus proxy refresh before upload.
## Open Decisions
* Target `ConfigPage.vue` exact migration is rejected for this task. Its grouping idea is useful, but the component depends on target-only `/api/config/runtime` and `/api/config/source` endpoints, keeps a raw `.env` editor, and reintroduces dark glass / emoji styling. A current-style runtime configuration page can be a separate frontend/API safety task, not a direct parity copy.* Target `ThemeToggle.vue` remains rejected for this project because it reintroduces dark gradient / emoji styling that the current project intentionally moved away from.* Target's old positional `SignupProfile("Name", year, month, day, age)` public constructor remains rejected. Current repo keeps the stronger immutable `SignupProfile(full_name, birthday, age=...)` snapshot contract; the underlying birthday/age/profile propagation behavior is covered by current tests.* Remaining target auth-repair assertions after the migrated safe helper subsets are not a blanket migration target: * target's persisted `"auth_pending"` literal is intentionally rejected because current repo maps that lifecycle state to persisted `STATUS_AUTH_INVALID` (`"auth_invalid"`) and lets the account-state machine treat it as auth pending; * target's exact `update_account(email, {"status": ...})` call-shape assertions conflict with current `_reason`-carrying state-machine transition logging; * target's add-phone retry-disabled "pause without release" behavior is rejected for current automated provider children because it can leave an unrepairable child occupying one of the two managed seats under the hard Team cap. Current capacity-first release behavior is retained.
## Out of Scope For This Audit Pass
* Raising the Team seat cap above `1 owner + 2 managed children`.* Resetting or cleaning the dirty worktree.* Git commit and push are now in scope for the final repository handoff because the user explicitly requested them on 2026-05-20.* Mutating live remote services such as CPA, Sub2API, Cloudflare DNS, or OpenAI Team.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624# autoteam-1 full parity matrix
Date: 2026-05-19
## Objective Restatement
User objective: absorb all good points from `D:\Desktop\autoteam-1\AutoTeam` intothe current repo `D:\Desktop\AutoTeam`.
Concrete success criteria:
1. Every recent target-repo improvement is mapped to current code, tests, specs, or an explicit migration decision.2. Existing current-repo superior/incompatible implementations are preserved.3. Remaining gaps become small implementation slices, not whole-file overwrites.4. The final completion decision must be based on real artifacts and test/runtime evidence, not on commit count or broad similarity.
## Target Recent Commit Matrix
Target recent commits inspected with `git -C D:/Desktop/autoteam-1/AutoTeam show --stat --oneline`:
| Target commit | Capability | Current evidence | Status | Notes || --- | --- | --- | --- | --- || `8f17448 fix: add CPA credential gate to auto-check` | auto-check should consider read-only CPA provider-auth availability when Team is full but local active children are short | `src/autoteam/api.py::_collect_cpa_credential_gate`, auto-fill branch, `tests/unit/test_api_status.py::test_auto_check_uses_read_only_cpa_gate_when_team_full_and_no_credentials`, `test_auto_check_cpa_gate_does_not_treat_management_failure_as_zero_credentials` | Absorbed by adapted design | Current repo keeps command `auto-fill` / `cmd_rotate(..., background_post_sync=True)` rather than target's larger auto-check restructuring. Gate is read-only and does not call CPA sync/upload/delete, and the same live provider-auth truth now also drives active CPA publish routing in `src/autoteam/cpa_sync.py`. || `276ed0b fix: harden quota blocker rotation` | quota blocker replacement, auto-check action semantics | `src/autoteam/manager.py` has `_replaceable_pool_blocker_reason`, `_wait_for_remote_capacity_after_removal`, `_validate_managed_account_operational`; tests in `tests/unit/test_manager_rotate.py` and `tests/unit/test_api_status.py` | Absorbed in `05bf6da` | Need no whole-file copy. || `f120570 fix rotate post sync and cliproxy health` | deferred rotate post-sync and read-only CLIProxy health | `src/autoteam/cliproxy_health.py`, `/api/status.cliproxy`, `tests/unit/test_cliproxy_health.py`, `tests/unit/test_manager_rotate.py` | Absorbed | Current repo keeps read-only health and CPA delete guard. || `6f4d106 fix invite blank page recovery` | recover post-auth blank registration pages | `src/autoteam/invite.py` has `_recover_blank_invite_page`; tests in `tests/unit/test_invite_blank_page_recovery.py` | Absorbed | Current tests are split from target `test_signup_flow_profiles.py`, but cover the same blank-page recovery behavior. || `15e50d6 Improve registration credential sync and diagnostics` | sync newly ready credential once, improve CPA/Sub2API diagnostics | `src/autoteam/manager.py` has `_sync_ready_credential_to_targets`; `src/autoteam/sync_targets.py` has `sync_account_to_configured_targets`; tests in `test_sync_targets.py`, `test_cpa_sync.py`, `test_sub2api_sync.py` | Mostly absorbed | Further audit should compare target invite diagnostics line-by-line before declaring final completion. || `d952ce6 fix rotation cooldown safety boundary` | cooldown must not block real shortage | `tests/unit/test_api_status.py` includes shortage/cooldown and blocker replacement cases | Absorbed | Strengthened in `05bf6da`. || `2fb3031 fix rotation validation and ipv6 pool status` | `/api/status` runtime/IPv6/rotation validation fields | current `api.py`, `ipv6_pool.py`, `tests/unit/test_api_status.py`, `tests/unit/test_ipv6_pool.py` | Absorbed | Current repo also has richer IPv6 proxy isolation task artifacts. || `7d46b46 fix autoteam seat rotation runtime hardening` | runtime resources, Playwright cleanup, Docker bounds, rotation contract, safer Team/account cleanup helpers | current prior commits and specs: `runtime-docker-hardening.md`, `free-registration-hardening.md`; `src/autoteam/account_ops.py`, `/api/team/members`, `tests/unit/test_account_ops.py` | Absorbed core plus account-ops slice | Docker live deployment was intentionally not restarted in current repo. || `dafa32f fix: preswitch exhausted accounts in seat-2 rotation` | pre-switch exhausted child before replacement | current `cmd_rotate` intentionally uses safer remove-before-create for replaceable blockers; `tests/unit/test_manager_rotate.py::test_cmd_rotate_target2_refills_after_exhausted_removal_despite_transient_overcount` covers exhausted target-2 refill order | Absorbed by adapted design | Do not copy target preswitch because it can temporarily exceed the Team cap. Current regression asserts remove before replacement. || `89932b2 Fix seat-2 preswitch transient overcount cleanup` | cleanup overcount after preswitch | current `cmd_rotate` uses conservative `min(api_count, initial_api_count - removed_now)` after removal; regression test injects stale `api_count=3` and still refills from standby | Absorbed by adapted design | Target overcount risk is covered without creating a transient over-cap state. || `123e80f Add configurable auto-check seats and seat-2 preswitch` | target seat config, settings UI, preswitch | current `.env.example` and API clamp target seats to 1..3; `Settings.vue` has auto-check target controls | Mostly absorbed | Preswitch exactness remains the only uncertain part. || `a0c852f fix-add-phone-auth-retry` | add-phone auth retry backoff | current `AUTO_CHECK_RETRY_ADD_PHONE`, `AUTO_CHECK_ADD_PHONE_MAX_RETRIES`, auth repair tests | Absorbed | Current account-state work appears richer. || `e9d614f feat: add account disable and bulk toggle controls` | disable/bulk enable UI/API and sync exclusion | current `accounts.is_account_disabled`, `/api/accounts/*/disable`, bulk endpoints, `Dashboard.vue`, tests in `test_accounts.py`, `test_api_status.py`, `test_cpa_sync.py`, `test_sub2api_sync.py` | Absorbed | Current frontend style is different but functionality exists. || `6fa85a5 Update main codex remote deletion targets` | Main-Codex local-only login path, sync-target preflight, and remote deletion across CPA/Sub2API | `src/autoteam/codex_auth.py::MainCodexLoginFlow`, `src/autoteam/api.py` routes `/api/main-codex/login`, `/api/main-codex/delete-remote-files`, `/api/main-codex/delete-cpa`, tests in `tests/unit/test_api_main_codex_after_admin.py` and `tests/unit/test_round10_master_codex_session.py` | Absorbed by adapted design | Current repo uses `sync_targets.py` configured-target router and keeps admin-login local auth refresh without remote sync. || `66249a9 feat: add dashboard quota reset action` | Reset local quota recovery metadata and recover exhausted rows to checkable local states | `manager.cmd_reset_quota_recovery`, CLI `reset-quota`, API `POST /api/tasks/reset-quota`, `tests/unit/test_manager_reset_quota.py`, `tests/unit/test_api_status.py` | Absorbed | Current behavior is local-only: no Team/CPA/Sub2API mutation. || `563e8bc Randomize signup profile details` | randomized signup profile consistency | current `SignupProfile` and profile-propagation tests in `test_round12_s3_cherry_pick.py`, `test_free_registration_hardening.py` | Partially absorbed / needs assertion audit | Target's public dataclass shape differs; do not change current immutable profile contract without auditing all free-registration callers. || `5782586 fix: harden codex team workspace selection` | workspace selection, signup-flow helper, and session Codex auth hardening | current `oauth_workspace.py`, `SessionCodexAuthFlow`, `chatgpt_api._workspace_candidate_kind`, `ChatGPTTeamAPI._wait_for_post_workspace_ready`, `codex_auth` compatibility wrappers/lightweight OAuth helpers/session fallback, direct/invite split-code helpers, `tests/unit/test_workspace_oauth_parity.py` | Absorbed by adapted design | Target `test_chatgpt_workspace.py`, `test_codex_auth_session.py`, and all non-profile-shape assertions from target `test_signup_flow_profiles.py` now pass against current. Remaining target signup-flow failures are the rejected old positional `SignupProfile` constructor shape only. |
## Target-only Files And Migration Decisions
Target-only files from `git ls-files` comparison:
| Target-only artifact | Current equivalent | Decision || --- | --- | --- || `src/autoteam/cloudflare_temp_email.py` | `src/autoteam/cloudflare_temp_email.py` facade plus `src/autoteam/mail/cf_temp_email.py` and `MAIL_PROVIDER` / `MAIL_PROVIDER_CHAIN` | Absorbed as compatibility facade; source of truth remains provider package | Current implementation supports cf_temp_email under a provider package and adds maillab/addy/simplelogin fallback. The top-level module is a legacy import shim only, not a move back to target's simpler architecture. || `src/autoteam/mail_provider.py` | `src/autoteam/mail/__init__.py`, `mail/base.py`, `mail/fallback.py`, provider modules | Superseded. Target helper is simpler; current abstraction is stronger. || `src/autoteam/cloudflare_dns.py` | `src/autoteam/dns_diagnostics.py`, `/api/setup/dns/check`, `tests/unit/test_dns_diagnostics.py` | Read-only portion migrated. The mutating `upsert_record` / `ensure_admin_dns` path remains rejected unless the user explicitly asks for DNS automation. || `web/src/components/ConfigPage.vue` | current `SetupPage.vue`, `Settings.vue`, `MailProviderCard.vue` | UX grouping useful, exact component not migrated | Target's unified runtime/source configuration grouping is useful, especially category tabs and `.env` source editing. The exact file is dark, emoji-heavy, and depends on `/api/config/runtime` plus `/api/config/source`; migrate only after a separate current-style safety/design pass. || `web/src/components/ThemeToggle.vue`, `web/src/theme.js` | no direct current equivalent | Reject for now. Target implementation reintroduces dark gradient/emoji styling that conflicts with current UI direction. || `tests/unit/test_account_ops.py` | `tests/unit/test_account_ops.py` | Migrated. Current tests cover target assertions plus current `/api/team/members` normalized rendering. Target test file also passes against current code. || `web/pnpm-lock.yaml`, `web/public/favicon.svg`, `src/autoteam/web/dist/assets/*`, `src/autoteam/web/dist/favicon.svg` | current web build pipeline, `web/package-lock.json`, regenerated `src/autoteam/web/dist/*` | Superseded as build artifacts | These are target build outputs or lockfile assets, not feature-source truth. Current repo regenerates its own web build artifacts and keeps `web/package-lock.json`; do not copy target build outputs verbatim. || `test_signup_profile.py` | `test_round12_s3_cherry_pick.py`, `test_free_registration_hardening.py`, `src/autoteam/signup_profile.py` | Superseded by current shape | Target file fails against current immutable snapshot interface because current repo intentionally keeps `SignupProfile(full_name, birthday, age="...")` plus `birthday_text` / `age_text`; the underlying behavior (deterministic generation, immutability, positional birthday ordering, RNG injection) is already covered in current tests. || `test_chatgpt_workspace.py` | `tests/unit/test_workspace_oauth_parity.py`, `src/autoteam/chatgpt_api.py` | Migrated | Target file now passes against current repo. Current coverage keeps workspace noise filtering, fallback classification, post-selection readiness, and completed ChatGPT home shortcut behavior. || `test_codex_auth_session.py` | `tests/unit/test_workspace_oauth_parity.py`, `tests/unit/test_round11_oauth_workspace_consent.py`, `src/autoteam/oauth_workspace.py`, `src/autoteam/codex_auth.py` | Migrated core workspace/session assertions | Target file now passes against current repo. Current repo keeps shared implementation in `oauth_workspace.py` and exposes thin compatibility wrappers from `codex_auth.py`. || `test_signup_flow_profiles.py` | `test_free_registration_hardening.py`, `test_round12_s3_cherry_pick.py`, `test_workspace_oauth_parity.py`, `src/autoteam/codex_auth.py`, `src/autoteam/invite.py`, `src/autoteam/manager.py` | Absorbed except rejected old profile constructor shape | Current repo covers snapshot propagation, about-you retries, workspace/OAuth selection, split-code target waits, direct/invite code submit helpers, OAuth lightweight recovery, OTP rejection cache, session-bundle extraction, and `login_codex_via_browser(return_result=..., pre_signed_in_cookies=...)`. Full target file now reaches `24 passed, 11 failed`; every remaining failure is the old positional `SignupProfile("Name", year, month, day, age)` API, which current repo intentionally rejects in favor of the immutable mapping snapshot contract. || `test_manager_auth_repair.py` | `tests/unit/test_manager_auth_paths.py`, auth-repair related tests in `tests/unit/test_round12_s3_cherry_pick.py` and `tests/unit/test_api_status.py` | Safe auth-path/result-helper/cmd-check/release-policy subsets migrated; exact target status literal remains rejected | Current now resolves host, container, project-relative, and bare auth-file paths, protects Team seats when a real local auth exists, exposes `_login_codex_with_result()` with target-compatible retry/result behavior, lets `cmd_check(...force_auth_repair...)` ignore cooldown, preserves historical low-quota candidates on network errors, releases repeated email-verification and missing-auth `login_state_lost` blockers, retires released failed repairs, and preserves protected local credentials. The full target file still has incompatible expectations around the target-only `"auth_pending"` persisted literal, exact `update_account()` call shape without `_reason`, and add-phone retry-disabled no-release behavior. Those are rejected for current's state machine and capacity-first hard-cap policy. || `test_cloudflare_temp_email.py` | `src/autoteam/cloudflare_temp_email.py`, `src/autoteam/mail/base.py`, `src/autoteam/mail/cf_temp_email.py`, current `tests/unit/test_cloudmail.py` | Absorbed as compatibility facade + metadata-preferred extraction | Current repo now keeps the provider-package source of truth, but exposes a target-compatible top-level compatibility module, strips `/admin` from the base URL, and prefers `metadata.ai_extract` before subject/body parsing for OTP and invite extraction. |
## Current-only Strengths To Preserve
* `src/autoteam/mail/` package with provider fallback chain and richer provider options.* Account-state lifecycle tests and reconciliation anomaly tests.* Multi-master workspace pool and direct-parallel budget propagation.* Frontend component system (`AtButton`, status/health components, composables) and cleaner UI direction.* CPA delete guard and disabled-account exclusion.* `1 owner + 2 managed children = 3 seats` hard cap.
## Recommended Next Slice
Slice P1: seat-2 preswitch transient-overcount coverage audit and regression tests. **Completed in this task.**
Reason:
* It is close to the just-landed rotation work and still marked partially absorbed.* It can be verified entirely with unit tests.* It avoids high-risk live operations and avoids touching frontend style.
Slice P2: Cloudflare DNS read-only diagnostics. **Completed in this task.**
Reason:
* It is the clearest target-only useful source helper.* Current docs still instruct manual DNS setup.* Only read-only `check_admin_dns` should be migrated first; mutating `ensure_admin_dns` should remain out of scope until the user explicitly wants DNS automation.
Slice P3: account cleanup and Team response shape hardening. **Completed in this task.**
Reason:
* Target `tests/unit/test_account_ops.py` exposed a useful safety surface that was not covered in current repo before this slice.* The migration is backend-only and does not touch live remote services.* Current repo keeps its stronger `src/autoteam/mail/` provider package and `sync_targets.py` router instead of copying target top-level `mail_provider.py`.
Implemented current evidence:
* `src/autoteam/account_ops.py` now parses Team member/invite wrapper variants, nested `user` / `account_user` fields, readable auth/HTML failures, invite delete fallback, local credential seat protection, configured CPA/Sub2API deletion, and generic `mail_account_id` / legacy `cloudmail_account_id` deletion.* `src/autoteam/api.py` `/api/team/members` now renders normalized nested Team rows using the same helpers rather than assuming top-level fields.* `.trellis/spec/backend/account-disable-cpa-sync.md` records the executable contract for deletion and Team state parsing.
Slice P4: CPA credential gate for auto-check. **Completed in this task.**
Reason:
* Target commit `8f17448` was newer than the previous matrix and exposed a real remaining runtime-decision gap.* Current repo already has read-only CLIProxyAPI health, so the useful value is the gate decision, not new remote mutation behavior.* It can be tested without touching live CPA/Sub2API/Team.
Implemented current evidence:
* `src/autoteam/api.py::_collect_cpa_credential_gate()` checks only configured CPA enablement plus read-only `get_cliproxy_health(cache_ttl=0.0, force_refresh=True)`.* `src/autoteam/api.py::_auto_check_loop()` now lets zero available CPA provider credentials trigger the existing `auto-fill` path when Team is full but local active children are below target.* Management failure returns `zero_available=false`; it is not treated as no credentials.* `.trellis/spec/backend/runtime-docker-hardening.md` records the read-only gate contract.
Slice P5: reset-quota local recovery. **Completed in this task.**
Reason:
* Target commit `66249a9` exposed a useful operator recovery action after quota reset windows or stale exhausted metadata.* The current migration is local-only and does not mutate Team, CPA, Sub2API, or browser sessions.
Implemented current evidence:
* `src/autoteam/accounts.py` defines `STATUS_AUTH_PENDING` as an alias for the persisted `auth_invalid` lifecycle state.* `src/autoteam/manager.py::cmd_reset_quota_recovery()` clears local quota reset metadata for non-main accounts and restores exhausted rows to either `active` when an auth file exists or `auth_pending`/`auth_invalid` when it does not.* `src/autoteam/api.py` exposes `POST /api/tasks/reset-quota`.* `tests/unit/test_manager_reset_quota.py` covers local-only state transitions.
Slice P6: main-Codex local login and remote deletion target router. **Completed in this task.**
Reason:
* Target commit `6fa85a5` and target-only `tests/unit/test_api_main_codex_after_admin.py` exposed a useful split between local main-Codex login and explicit remote sync/delete actions.* The migration is safe when adapted to current `sync_targets.py`: sync and delete remain explicit operator actions, while admin-login local refresh does not upload or delete CPA/Sub2API files.
Implemented current evidence:
* `src/autoteam/codex_auth.py::MainCodexLoginFlow` saves a main auth file without remote sync; `MainCodexSyncFlow` extends it and still syncs only on the sync path.* `src/autoteam/api.py` now tracks `main_codex.action`, exposes `POST /api/main-codex/login`, requires enabled sync targets before `POST /api/main-codex/start`, and adds explicit remote deletion routes `/api/main-codex/delete-remote-files` plus legacy `/api/main-codex/delete-cpa`.* `web/src/api.js` exposes client helpers for the new routes without adding a new UI surface yet.* `.trellis/spec/backend/runtime-docker-hardening.md` records the local-login, sync-target preflight, and explicit-delete contracts.
Slice P7: manager auth-path resolution and protected Team credential recovery.
Reason:
* Target `test_manager_auth_repair.py` exposed a low-risk current gap: manager code did not consistently resolve auth paths persisted as container paths, project-relative paths, or bare filenames.* The migration is local-file and reconciliation only. It does not mutate Team, CPA, Sub2API, or browser sessions.* It strengthens the current account-state lifecycle without copying target's larger auth-repair command shape.
Implemented current evidence:
* `src/autoteam/manager.py::_resolve_auth_file_path()` handles host absolute paths, `/app/...` container paths, `data/auths/...`, `auths/...`, and bare names searched under current auth dirs.* `src/autoteam/manager.py::_find_team_auth_file()` now searches the current auth search dirs instead of only one path convention.* `sync_account_states()` now preserves Team seats for standby/auth-pending rows with real local auth files and restores recovered Team rows with `protect_team_seat=True` plus `workspace_account_id`.* `tests/unit/test_manager_auth_paths.py` covers the adapted behavior.
Remaining target auth-repair audit:
* Full target `test_manager_auth_repair.py` still fails against current because several assertions describe target-only helper names or behavior policies, not simple path handling.* Do not migrate those as a batch. Each remaining category needs a separate behavior decision against current account-state and hard Team-cap contracts.
Slice P8: OAuth/auth-repair transient error labels and retry-delay helper. **Completed in this task.**
Reason:
* Target `test_manager_auth_repair.py::test_auth_repair_error_label_handles_oauth_timeout` exposed a small diagnostic gap with no remote mutation risk.* Current repo already has auth-repair retry metadata; richer labels make cooldown and pause messages more actionable without changing the state machine.
Implemented current evidence:
* `src/autoteam/manager.py::_auth_repair_error_label()` now labels `oauth_timeout`, `unsupported_region`, `account_selection`, `missing_auth_file`, and `auth_error_discard`.* `src/autoteam/manager.py::_oauth_retry_delay_seconds()` records the short same-round delays target uses for transient organization/region pages.* `tests/unit/test_round12_s3_cherry_pick.py` covers the adapted label and delay contract.
Slice P9: workspace selection and session Codex helper parity. **Completed in this task.**
Reason:
* Target `test_chatgpt_workspace.py` and `test_codex_auth_session.py` exposed a behavior gap: current had the stronger shared `oauth_workspace.py` helpers but did not expose target-compatible wrappers from `codex_auth.py`, and `ChatGPTTeamAPI.select_workspace_option()` did not wait for post-selection ChatGPT readiness before reclassifying the login step.* The migration is pure helper/UI-flow hardening and is unit-testable without live browser or remote services.
Implemented current evidence:
* `src/autoteam/chatgpt_api.py` now classifies workspace labels through `_workspace_candidate_kind()`, filters page heading/legal-link noise, marks personal/free/new-org options as fallback, waits for post-workspace readiness, and returns completed when the page has already landed on ChatGPT home.* `src/autoteam/codex_auth.py` exposes compatibility wrappers around the shared `oauth_workspace.py` detector/candidate/selector functions.* `tests/unit/test_workspace_oauth_parity.py` keeps current regression coverage.* Target `test_chatgpt_workspace.py` and `test_codex_auth_session.py` pass against current repo after this migration.
Slice P10: target ConfigPage UX audit.
Reason:
* Target's grouping of runtime config into mail, sync, security, admin, auto-check, source, and proxy categories is useful.* Current repo already has a stronger `SetupPage` / `Settings` / `MailProviderCard` split and a cleaner restrained UI direction.* The exact target component should not be copied: it uses dark glass cards, emoji category icons, gradient accents, and depends on target-only `/api/config/runtime` plus `/api/config/source` endpoints.* Future migration, if desired, should be a current-style runtime configuration pass with explicit source-editor safety review, not a whole-file copy.* Source check on 2026-05-19 confirmed target frontend clients call `/api/config/runtime` and `/api/config/source`, and target backend implements those endpoints as runtime config read/write plus raw `.env` source read/write. Current repo intentionally exposes narrower setup/runtime endpoints such as `/api/config/register-domain`, `/api/config/preferred-seat-type`, `/api/config/sync-probe`, and `/api/config/auto-check`, and `web/src/api.js` has no runtime/source config client. Exact target UI/API migration would therefore be a new source-editor safety feature, not a parity patch.
Slice P11: Codex OAuth lightweight challenge/recovery helpers. **Completed in this task.**
Reason:
* Target `test_signup_flow_profiles.py` exposed a safe helper subset that improves Codex OAuth robustness without changing live browser-login orchestration or session-bundle extraction policy.* The migration is DOM/trace/cache helper hardening only: organization dropdown selection, choose-account selection, OAuth trace filtering, retryable error classification, timeout/no-valid-organization retry-page recovery, login challenge completion, OTP rejection cache hashing, and OTP submit acceptance of OAuth progress URLs.* Higher-risk target helpers remain out of this slice: split verification-code target waits, `_fetch_team_session_bundle_from_context`, `login_codex_via_browser(return_result=..., pre_signed_in_cookies=...)`, and the rejected old `SignupProfile` constructor shape.
Implemented current evidence:
* `src/autoteam/codex_auth.py` now contains the lightweight OAuth helpers and bounded trace/cache constants.* `tests/unit/test_workspace_oauth_parity.py` covers the current-adapted helper behavior with Playwright-like fake locators whose empty `.first` is not visible.* The selected target subset from `test_signup_flow_profiles.py` passes against current repo (`13 passed`).
Slice P12: direct/invite split-code verification helpers. **Completed in this task.**
Reason:
* Target `test_signup_flow_profiles.py` exposed a real registration robustness gap: OpenAI email verification can render delayed six-box inputs, and current invite registration previously logged only a generic missing-input warning.* The migration is DOM-bound helper hardening. It does not alter seat caps, remote sync, CPA/Sub2API behavior, or browser-login policy.
Implemented current evidence:
* `src/autoteam/manager.py` now exposes `_DIRECT_MULTI_CODE_SELECTOR`, `_wait_for_direct_code_target()`, and `_submit_direct_verification_code()`. The direct flow waits for delayed split/single code inputs before submitting.* `src/autoteam/invite.py` now exposes `INVITE_CODE_SELECTORS`, `INVITE_MULTI_CODE_SELECTOR`, `_wait_for_invite_code_target()`, `_submit_invite_verification_code()`, and structured input diagnostics for timeout/advanced-step cases.* `tests/unit/test_workspace_oauth_parity.py` covers delayed split-code helper behavior in the current repo.* Selected target split-code assertions from `test_signup_flow_profiles.py` pass against current repo (`5 passed`).
Slice P13: Codex session fallback from pre-signed ChatGPT cookies. **Completed in this task.**
Reason:
* Target `test_signup_flow_profiles.py` showed a useful safe path for newly registered accounts: if a valid ChatGPT Team session already exists in the browser context, fetch `/api/auth/session` and use that Team access token before entering the full OAuth challenge path.* The migration is opt-in and backwards-compatible: existing callers still get the old bundle/`None` return shape unless they explicitly pass `return_result=True`; session fallback is attempted only when `pre_signed_in_cookies` is provided.
Implemented current evidence:
* `src/autoteam/codex_auth.py::_fetch_team_session_bundle_from_context()` injects Team account cookies, opens `https://chatgpt.com/admin/workspace/<account_id>`, extracts `/api/auth/session.accessToken`, validates Team JWT claims, and can accept a quota-verified session token whose JWT workspace claim is stale.* `login_codex_via_browser(..., pre_signed_in_cookies=..., return_result=True)` returns the target-compatible `{ok, bundle, error_type, error_detail, retryable}` shape on the explicit session-fallback path while preserving the default return contract.* `tests/unit/test_workspace_oauth_parity.py` covers pre-signed session fallback in the current repo.* Selected target session fallback assertions from `test_signup_flow_profiles.py` pass against current repo (`4 passed`).
Slice P14: Codex auth-repair result wrapper helper. **Completed in this task.**
Reason:
* Target `test_manager_auth_repair.py` exposed one safe auth-repair helper that can be migrated without changing `cmd_check`, account-state lifecycle, or Team-seat release decisions.* `_login_codex_with_result()` is a local normalization wrapper around the already migrated `login_codex_via_browser(..., return_result=True)` contract. It can be tested with pure monkeypatched unit tests and does not touch live browser, Team, CPA, Sub2API, or Cloudflare state.* Higher-risk target auth-repair behavior remains outside this slice: `cmd_check(...force_auth_repair...)`, historical low-quota network-error replacement policy, retry-disabled add-phone no-release behavior, `auth_pending` literal expectations, repeated email-verification release, and local-credential `login_state_lost` pause/release policy.
Implemented current evidence:
* `src/autoteam/manager.py::_login_codex_with_result()` now normalizes explicit `{ok, bundle, error_type, error_detail, retryable}` results, legacy bundle/`None` results, thrown exceptions, and non-Team bundles into one result shape with `attempts`.* `AUTH_REPAIR_SINGLE_ATTEMPT_FAILURE_TYPES` prevents same-round retries for failures that should be handled by the surrounding auth-repair state machine, while retryable `auth_code_missing` can retry within the same call.* `tests/unit/test_round12_s3_cherry_pick.py::TestLoginCodexWithResult` covers retryable same-round success, single-attempt terminal categories, and non-Team bundle rejection.* The selected target `_login_codex_with_result` assertions from `test_manager_auth_repair.py` pass against current repo (`5 passed`).* After P14, full target `test_manager_auth_repair.py` reached `14 passed, 13 failed`; the remaining failures were the higher-risk policy categories listed above and were intentionally split into later slices.
Slice P15: `cmd_check` auth-repair entry and historical-low-quota handling. **Completed in this task.**
Reason:
* Target `test_manager_auth_repair.py` exposed useful `cmd_check` behavior that is safe when adapted to current state aliases and mail-provider routing: force-auth-repair should ignore cooldown, auth-pending rows should be scanned, and low historical quota should be usable when the live quota endpoint returns a temporary network error.* The migration is local decision logic only. It does not change Team-seat release policy, CPA/Sub2API sync, live Docker state, or the hard `1 owner + 2 managed children` cap.
Implemented current evidence:
* `src/autoteam/manager.py::cmd_check()` now accepts `force_auth_repair=False`, `preserve_low_active=False`, and `preserved_low_accounts=None` while preserving the legacy positional `include_standby` parameter.* `_is_auth_repair_pending_status()` accepts both current persisted `STATUS_AUTH_INVALID` and the target legacy `"auth_pending"` literal as input. Output still uses current `STATUS_AUTH_INVALID`.* `_historical_low_quota_info()` derives a bounded low-quota decision from saved `last_quota` only when the reset window has not elapsed.* `preserve_low_active=True` records low active accounts in `preserved_low_accounts` instead of immediately marking them exhausted; default mode can still mark historical-low accounts exhausted.* `force_auth_repair=True` bypasses retry cooldown/paused skips, uses `_get_account_mail_client()` for per-account mail-provider routing, and calls `_login_codex_with_result()` without passing empty proxy kwargs to old monkeypatch/test doubles.* Selected target `cmd_check` auth-repair assertions now pass against current repo (`6 passed`).
Slice P16: `_record_auth_repair_failure` safe release-policy subset. **Completed in this task.**
Reason:
* Target auth-repair work contains one useful seat-rotation safety improvement: when a repair failure has actually released a Team seat, the local row should not silently re-enter standby reuse.* Current repo already has protected local credential rules. Target's `login_state_lost` guard was adapted to preserve those local credentials rather than releasing them.* The migration deliberately does not adopt target's persisted `"auth_pending"` literal or exact `update_account()` call shape because current account-state transition logging relies on `STATUS_AUTH_INVALID` plus `_reason`.
Implemented current evidence:
* `src/autoteam/manager.py` now defines release-after-retry and Team-blocker classifications for auth repair.* Repeated `email_verification` can pause and release after the retry budget is exhausted.* Missing-auth `login_state_lost` can release the Team blocker; protected local credential seats cancel release and remain in current auth-pending state.* Released repair failures are marked `disabled=True`, `reuse_disabled=True`, and `retired_reason="auth_repair_failed:<type>"`, then account IPv6 proxy state is released best-effort.* Current `TestRecordAuthRepairFailure`, `TestLoginCodexWithResult`, `TestCmdCheckAuthRepairEntry`, `test_api_status`, and `test_round12_wireup` suites pass.* Full target `test_manager_auth_repair.py` now reaches `20 passed, 7 failed`. Remaining failures are the intentionally rejected `"auth_pending"` persisted literal, exact update-call shape, and add-phone retry-disabled no-release policy. Current keeps capacity-first release for unrepairable managed children.
Slice P17: Cloudflare temp-email compatibility facade and metadata-preferred extraction. **Completed in this task.**
Reason:
* Target `test_cloudflare_temp_email.py` exposed a small compatibility gap: the current project already had a stronger `src/autoteam/mail/` provider package, but not the legacy top-level import path or the target's `/admin` base URL normalization behavior.* The useful part of the target behavior is not the top-level architecture; it is the provider parsing improvement. Metadata-derived `ai_extract` results should win over subject/body fallback parsing because they are more direct and less brittle.
Implemented current evidence:
* `src/autoteam/cloudflare_temp_email.py` now exposes a target-compatible `CloudflareTempEmailClient` wrapper while keeping `src/autoteam/mail/cf_temp_email.py` as the source of truth.* `normalize_cloudflare_temp_email_base_url()` strips `/admin` and trailing slashes from target-style inputs.* `src/autoteam/mail/base.py` now prefers `metadata.ai_extract.result` for both verification code and invite-link extraction before falling back to text/body parsing.* Current `tests/unit/test_cloudmail.py` covers the compatibility facade and metadata-preferred extraction behavior.* Target `tests/unit/test_cloudflare_temp_email.py` now passes against current repo (`6 passed`), and the combined current cloudmail/mail sniff suite still passes.
Slice P18: active CPA credential publish preflight. **Completed in this task.**
Reason:
* Target `8f17448` made CPA provider-auth availability a real-time decision input for auto-check. The same principle must also hold when current repo publishes active auth files to CPA: local `STATUS_ACTIVE` is not enough evidence that a credential should be uploaded or that its remote copy should be removed.* The current migration is adapted to existing CPA delete guards. A quota network failure is treated as "unknown, keep remote", not "zero usable" and not "delete remote".
Implemented current evidence:
* `src/autoteam/cpa_sync.py::_active_auth_publish_decision()` reads each active auth file and calls `check_codex_quota(access_token, timeout=8)` immediately before publish.* `sync_to_cpa()` uploads only `ok` active credentials, preserves remote files on `network_error` / quota exceptions, and routes exhausted or terminal failures to the existing remote-delete path.* `sync_to_cpa()` now returns `active_publish.skipped_unknown`, `active_publish.kept_remote`, and `active_publish.delete_remote` counters so operators can see why active files were not uploaded.* `tests/unit/test_cpa_sync.py` covers exhausted active credentials deleting the matching remote file, network-error active credentials preserving the remote copy, disabled-account preservation, and proxy refresh before upload.
## Commands/Evidence Collected
* `git -C D:/Desktop/autoteam-1/AutoTeam log --oneline -12`* `git log --oneline -12`* `git -C D:/Desktop/autoteam-1/AutoTeam show --stat --oneline ...`* `diff -qr --exclude=.git --exclude=__pycache__ --exclude=node_modules --exclude=dist ... src/autoteam`* `diff -qr --exclude=.git --exclude=__pycache__ --exclude=node_modules --exclude=dist ... web/src`* `rg` searches for blank-page recovery, blocker rotation, disable/bulk controls, sync diagnostics, and Cloudflare DNS/Temp Email.* `python -m ruff check src/autoteam/manager.py tests/unit/test_manager_rotate.py tests/unit/test_api_status.py`* `python -m pytest -q tests/unit/test_manager_rotate.py tests/unit/test_api_status.py` -> `21 passed, 1 warning`* `python -m ruff check src/autoteam/dns_diagnostics.py src/autoteam/api.py tests/unit/test_dns_diagnostics.py tests/unit/test_manager_rotate.py tests/unit/test_api_status.py`* `python -m py_compile src/autoteam/dns_diagnostics.py src/autoteam/api.py src/autoteam/manager.py`* `python -m pytest -q tests/unit/test_dns_diagnostics.py tests/unit/test_manager_rotate.py tests/unit/test_api_status.py` -> `27 passed, 1 warning`* `python -m pytest -q tests/unit/test_dns_diagnostics.py tests/unit/test_mail_provider_probe.py tests/unit/test_manager_rotate.py tests/unit/test_api_status.py` -> `38 passed, 1 warning`* `python -m ruff check src/autoteam/account_ops.py src/autoteam/api.py tests/unit/test_account_ops.py` -> pass* `python -m pytest -q tests/unit/test_account_ops.py` -> `8 passed, 1 warning`* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_account_ops.py` -> `7 passed`* `python -m pytest -q tests/unit/test_round6_patches.py tests/unit/test_spec2_lifecycle.py tests/unit/test_cpa_sync.py tests/unit/test_sub2api_sync.py` -> `66 passed, 1 warning`* `python -m pytest -q tests/unit/test_account_ops.py tests/unit/test_api_playwright_cleanup.py tests/unit/test_api_status.py tests/unit/test_manager_rotate.py` -> `43 passed, 1 warning`* `python -m ruff check src/autoteam/account_ops.py src/autoteam/api.py tests/unit/test_account_ops.py tests/unit/test_api_playwright_cleanup.py tests/unit/test_api_status.py tests/unit/test_manager_rotate.py tests/unit/test_round6_patches.py tests/unit/test_spec2_lifecycle.py tests/unit/test_cpa_sync.py tests/unit/test_sub2api_sync.py` -> pass* `python -m py_compile src/autoteam/account_ops.py src/autoteam/api.py` -> pass* `python -m ruff check src/autoteam/api.py tests/unit/test_api_status.py` -> pass* `python -m pytest -q tests/unit/test_api_status.py::test_auto_check_cooldown_does_not_delay_real_team_shortage tests/unit/test_api_status.py::test_auto_check_cooldown_keeps_full_team_from_refilling tests/unit/test_api_status.py::test_auto_check_cooldown_allows_full_team_blocker_replacement tests/unit/test_api_status.py::test_auto_check_uses_read_only_cpa_gate_when_team_full_and_no_credentials tests/unit/test_api_status.py::test_auto_check_cpa_gate_does_not_treat_management_failure_as_zero_credentials` -> `5 passed, 1 warning`* `python -m pytest -q tests/unit/test_api_status.py` -> `18 passed, 1 warning`* `python -m ruff check src/autoteam/accounts.py src/autoteam/manager.py src/autoteam/api.py tests/unit/test_manager_reset_quota.py tests/unit/test_api_status.py` -> pass* `python -m pytest -q tests/unit/test_manager_reset_quota.py tests/unit/test_api_status.py` -> `19 passed, 1 warning`* `python -m ruff check src/autoteam/api.py src/autoteam/codex_auth.py tests/unit/test_api_main_codex_after_admin.py tests/unit/test_round10_master_codex_session.py` -> pass* `python -m pytest -q tests/unit/test_api_main_codex_after_admin.py tests/unit/test_round10_master_codex_session.py` -> `14 passed, 1 warning`* `python -m ruff check src/autoteam/api.py src/autoteam/codex_auth.py src/autoteam/accounts.py src/autoteam/manager.py tests/unit/test_api_main_codex_after_admin.py tests/unit/test_round10_master_codex_session.py tests/unit/test_manager_reset_quota.py tests/unit/test_api_status.py` -> pass* `python -m pytest -q tests/unit/test_api_main_codex_after_admin.py tests/unit/test_round10_master_codex_session.py tests/unit/test_manager_reset_quota.py tests/unit/test_api_status.py tests/unit/test_sync_targets.py` -> `38 passed, 1 warning`* `npm run build` from `web/` -> Vite build succeeded; refreshed `src/autoteam/web/dist`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_api_main_codex_after_admin.py` -> `5 passed, 1 failed, 1 warning`. The failure is the target's exact `_finish_admin_login` expectation: current repo deliberately refreshes the local main auth file after admin login and records `main_auth` / `main_auth_error`; adapted current test asserts no remote sync instead.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_profile.py` -> `2 passed, 2 failed`. The failures are the target's older public shape (`age` as `int` and positional `SignupProfile(name, year, month, day, age)`), while current repo intentionally uses an immutable birthday mapping plus `age_text` for browser form consumers.* `python -m ruff check src/autoteam/manager.py tests/unit/test_manager_auth_paths.py` -> pass.* `python -m pytest -q tests/unit/test_manager_auth_paths.py` -> `4 passed`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_has_auth_file_resolves_container_data_auth_path D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_find_team_auth_file_searches_auth_dirs D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_sync_account_states_recovers_team_auth_file_as_protected D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_sync_account_states_promotes_auth_pending_remote_member_with_auth` -> `4 passed`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py` -> `8 passed, 19 failed, 1 warning`. Remaining failures are categorized above and should not be copied wholesale into current repo without separate behavior review.* `python -m ruff check src/autoteam/manager.py tests/unit/test_round12_s3_cherry_pick.py` -> pass.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_auth_repair_error_label_handles_oauth_timeout` -> `49 passed, 1 warning`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_chatgpt_workspace.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_codex_auth_session.py` before migration -> `3 passed, 9 failed`; failures were missing workspace helpers/wrappers.* `python -m ruff check src/autoteam/chatgpt_api.py src/autoteam/codex_auth.py tests/unit/test_workspace_oauth_parity.py` -> pass.* `python -m pytest -q tests/unit/test_workspace_oauth_parity.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_chatgpt_workspace.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_codex_auth_session.py tests/unit/test_round11_oauth_workspace_consent.py tests/unit/test_oauth_workspace_select.py` -> `45 passed`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py` -> `3 passed, 32 failed`. Remaining failures are split between rejected old `SignupProfile` constructor shape and separate OAuth challenge/session-bundle helper gaps.* `python -m ruff check src/autoteam/codex_auth.py tests/unit/test_workspace_oauth_parity.py` -> pass.* `python -m pytest -q tests/unit/test_workspace_oauth_parity.py` -> `6 passed`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_select_existing_api_organization_prefers_non_new_option D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_select_choose_account_prefers_matching_email D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_oauth_trace_filters_and_trims_relevant_urls D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_oauth_trace_detects_login_challenge_redirect D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_oauth_login_challenge_page_detects_log_in_url D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_complete_oauth_login_challenge_password_path D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_classify_oauth_failure_handles_no_valid_organizations D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_classify_oauth_failure_handles_timeout D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_recover_oauth_timeout_page_clicks_try_again D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_recover_oauth_no_valid_organizations_page_clicks_try_again D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_wait_for_otp_submit_result_accepts_oauth_progress_url D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_otp_rejection_cache_hashes_code_and_loads_recent D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_classify_oauth_failure_handles_unsupported_region` -> `13 passed`.* `python -m pytest -q tests/unit/test_workspace_oauth_parity.py tests/unit/test_round11_oauth_workspace_consent.py tests/unit/test_oauth_workspace_select.py tests/unit/test_round12_s3_cherry_pick.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_chatgpt_workspace.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_codex_auth_session.py` -> `95 passed, 1 warning`.* `python -m ruff check src/autoteam/manager.py src/autoteam/invite.py` -> pass.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_wait_for_direct_code_target_handles_delayed_split_inputs D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_wait_for_invite_code_target_handles_delayed_split_inputs D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_wait_for_invite_code_target_reports_advanced_step D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_register_with_invite_logs_code_input_diagnostics D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_submit_direct_verification_code_supports_split_inputs` -> `5 passed`.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_free_registration_hardening.py tests/unit/test_api_playwright_cleanup.py tests/unit/test_manager_fill.py` -> `74 passed, 1 warning`.* `python -m ruff check src/autoteam/codex_auth.py` -> pass.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_fetch_team_session_bundle_from_context_returns_team_token D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_fetch_team_session_bundle_rejects_non_team_token D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_fetch_team_session_bundle_accepts_quota_verified_session_token D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py::test_login_codex_via_browser_uses_session_fallback_before_oauth` -> `4 passed`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_signup_flow_profiles.py` -> `24 passed, 11 failed`. Remaining failures are all target's older positional `SignupProfile("Name", year, month, day, age)` API. Current repo intentionally keeps immutable `SignupProfile(full_name, birthday, age=...)` and already covers equivalent behavior in current tests.* `python -m ruff check src/autoteam/codex_auth.py src/autoteam/manager.py src/autoteam/invite.py tests/unit/test_workspace_oauth_parity.py` -> pass.* `python -m pytest -q tests/unit/test_workspace_oauth_parity.py` -> `8 passed`.* `python -m pytest -q tests/unit/test_workspace_oauth_parity.py tests/unit/test_round11_oauth_workspace_consent.py tests/unit/test_oauth_workspace_select.py tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_free_registration_hardening.py tests/unit/test_api_playwright_cleanup.py tests/unit/test_manager_fill.py tests/unit/test_round11_session_token_injection.py` -> `126 passed, 1 warning`.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py::TestLoginCodexWithResult` -> `5 passed`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_login_codex_with_result_retries_retryable_failures_within_same_round D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_login_codex_with_result_stops_immediately_on_hard_failure D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_login_codex_with_result_single_attempts_email_verification D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_login_codex_with_result_single_attempts_login_state_lost D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_login_codex_with_result_rejects_non_team_bundle` -> `5 passed`.* `python -m ruff check src/autoteam/manager.py tests/unit/test_round12_s3_cherry_pick.py` -> pass.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_workspace_oauth_parity.py tests/unit/test_api_status.py` -> `79 passed, 1 warning`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py` -> `14 passed, 13 failed, 1 warning`. Remaining failures are `cmd_check` signature/force-auth-repair/historical-low-quota behavior and `_record_auth_repair_failure` release/status policy differences, not the result-wrapper helper.* `python -m py_compile tests/unit/test_round12_s3_cherry_pick.py` -> pass.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py::TestCmdCheckAuthRepairEntry` -> `2 passed, 1 warning`.* `python -m ruff check src/autoteam/manager.py tests/unit/test_round12_s3_cherry_pick.py` -> pass.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py::TestLoginCodexWithResult tests/unit/test_round12_s3_cherry_pick.py::TestCmdCheckAuthRepairEntry tests/unit/test_api_status.py` -> `25 passed, 1 warning`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_preserves_active_credential_on_network_error D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_uses_historical_low_quota_on_network_error_for_remove_first D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_marks_historical_low_quota_exhausted_on_network_error D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_skips_cooled_down_auth_pending_account D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_force_auth_repair_ignores_cooldown D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_preserves_low_active_for_seat2_remove_first` -> `6 passed, 1 warning`.* `python -m py_compile src/autoteam/manager.py tests/unit/test_round12_s3_cherry_pick.py` -> pass.* `python -m ruff check src/autoteam/manager.py tests/unit/test_round12_s3_cherry_pick.py` -> pass.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py::TestRecordAuthRepairFailure` -> `8 passed, 1 warning`.* `python -m pytest -q tests/unit/test_round12_s3_cherry_pick.py::TestLoginCodexWithResult tests/unit/test_round12_s3_cherry_pick.py::TestCmdCheckAuthRepairEntry tests/unit/test_round12_s3_cherry_pick.py::TestRecordAuthRepairFailure tests/unit/test_api_status.py` -> `33 passed, 1 warning`.* `python -m pytest -q tests/unit/test_round12_wireup.py` -> `18 passed, 1 warning`.* `python -m ruff check src/autoteam/cloudflare_temp_email.py src/autoteam/mail/base.py src/autoteam/mail/cf_temp_email.py tests/unit/test_cloudmail.py` -> pass.* `python -m pytest -q tests/unit/test_cloudmail.py tests/unit/test_mail_cf_temp_email_sniff.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_cloudflare_temp_email.py` -> `27 passed in 0.16s`.* `python -m pytest -q tests/unit/test_cloudmail.py tests/unit/test_mail_cf_temp_email_sniff.py tests/unit/test_round12_s3_cherry_pick.py::TestRecordAuthRepairFailure tests/unit/test_round12_s3_cherry_pick.py::TestLoginCodexWithResult tests/unit/test_round12_s3_cherry_pick.py::TestCmdCheckAuthRepairEntry` -> `36 passed, 1 warning`.* `python -m pytest -q tests/unit/test_api_status.py tests/unit/test_round12_wireup.py tests/unit/test_manager_auth_paths.py tests/unit/test_manager_reset_quota.py` -> `41 passed, 1 warning`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_cloudflare_temp_email.py D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_preserves_active_credential_on_network_error D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_force_auth_repair_ignores_cooldown D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py::test_cmd_check_uses_historical_low_quota_on_network_error_for_remove_first` -> `9 passed, 1 warning`.* `python -m pytest -q D:/Desktop/autoteam-1/AutoTeam/tests/unit/test_manager_auth_repair.py` -> `20 passed, 7 failed, 1 warning`. Remaining failures are target-only `"auth_pending"` literal assertions, exact `update_account()` call-shape differences caused by current `_reason` state-machine logging, and the rejected add-phone retry-disabled no-release policy.* `python -m ruff check src/autoteam/codex_auth.py src/autoteam/cpa_sync.py src/autoteam/accounts.py src/autoteam/mail/__init__.py src/autoteam/manager.py tests/unit/test_cpa_sync.py tests/unit/test_free_registration_hardening.py tests/unit/test_round10_master_codex_session.py` -> pass.* `python -m pytest -q tests/unit/test_cpa_sync.py tests/unit/test_free_registration_hardening.py tests/unit/test_round10_master_codex_session.py tests/unit/test_api_status.py tests/unit/test_api_main_codex_after_admin.py tests/unit/test_manager_reinvite.py tests/unit/test_round12_wireup.py tests/unit/test_round11_oauth_failure_backoff.py tests/unit/test_round11_oauth_failure_kick_ws.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round11_fresh_relogin_fallback.py tests/unit/test_round11_oauth_workspace_consent.py tests/unit/test_round11_personal_oauth_retry.py` -> `132 passed, 1 warning`.
## Completion Audit Checklist
| Objective item | Evidence inspected | Result || --- | --- | --- || Map every recent target commit to current code/tests/spec or a decision | `Target Recent Commit Matrix` covers the latest target commits from `8f17448` through `5782586` and current commits from `efad4b5` backward | Complete || Classify target-only source/UI/test files | `Target-only Files And Migration Decisions` covers source helpers, UI components, target-only test files, lockfile/favicon/build artifacts | Complete || Absorb safe seat-rotation and account-state improvements | P1, P3, P4, P5, P7, P15, P16, P18 plus current tests and selected target tests | Complete || Preserve current stronger architecture | Current-only strengths section keeps mail provider package/fallback, account-state machine, multi-master pool, CPA delete guard, cleaner UI, and hard 3-seat cap | Complete || Avoid whole-file target copies | All slices are adapted helpers/tests/spec updates; target `ConfigPage.vue`, `ThemeToggle.vue`, old `SignupProfile` shape, and raw build artifacts are rejected | Complete || Avoid unsafe live mutations | No `/api/sync`, Docker restart, CPA/Sub2API/Cloudflare/OpenAI Team mutation, or remote deletion smoke test was used in this audit | Complete || Verify implementation with real commands | Commands/Evidence section records `ruff`, current pytest suites, and selected target pytest runs | Complete || Identify unresolved or rejected target assertions | Remaining target auth-repair failures are explicitly rejected as incompatible status literal/update-call/capacity-policy expectations | Complete |
## Completion Finding
The global objective for this audit pass is complete: every inspected targetrecent commit and target-only artifact is now either absorbed in current shape orexplicitly rejected as not suitable for this project. The broad seat-rotation core,preswitch/transient-overcount risk, target-only DNS helper value, account cleanup/ Team response-shape hardening, CPA credential gate logic, active CPA publishpreflight, reset-quota recovery, main-Codex local-login / remote-deletion behavior,auth-path credential recovery subset, OAuth diagnostic labels, workspace/sessionhelper parity, `cmd_check` auth-repair entry behavior, historical-low-quotarecovery, the safe `_record_auth_repair_failure` release-policy subset, andCloudflare temp-email compatibility/metadata extraction now have adaptedcurrent-repo implementations and tests. Target `ConfigPage.vue` is classified as"do not exact-copy; replan as a separate current-style config safety feature ifdesired." Target`test_signup_flow_profiles.py` is fully dispositioned: allnon-profile-shape behavior is absorbed, and the old positional `SignupProfile`constructor API is intentionally rejected. Remaining target auth-repair failuresare not incomplete work: target's `"auth_pending"` persisted literal is rejected,exact `update_account()` call-shape assertions conflict with currentstate-machine logging, and add-phone retry-disabled no-release behavior isrejected because it can leave an unrepairable child occupying scarce Teamcapacity under the current hard cap.31 unmodified lines3233343536373852 unmodified lines91929394959697989910010110210310410523 unmodified lines12913013112213213313413513613713813914014114214314414511 unmodified lines1571581591601611621631641651661671688 unmodified lines17717817918018118218318418518618718818919019119219331 unmodified linesSTATUS_PENDING = "pending" # 已邀请,等待注册完成STATUS_PERSONAL = "personal" # 已主动退出 team,走个人号 Codex OAuth,不再参与 Team 轮转STATUS_AUTH_INVALID = "auth_invalid" # auth_file token 已不可用(401/403),待 reconcile 清理或重登STATUS_AUTH_PENDING = STATUS_AUTH_INVALID # 向后兼容 target 命名,落盘值仍为 auth_invalidSTATUS_ORPHAN = "orphan" # 在 workspace 里占着席位,但本地没 auth_file(残废,待人工介入或兜底 kick)# Round 9 SPEC v2.0 — 母号 cancel_at_period_end 期内子号过渡态:# 仍持有有效 auth_file + token,wham 200 plan=team 可继续消耗配额;52 unmodified linesdef _normalize_account(acc: dict) -> dict: normalized = dict(acc or {}) normalized["disabled"] = bool(normalized.get("disabled", False)) normalized["mail_provider"] = str(normalized.get("mail_provider") or "").strip().lower() mail_account_id = normalized.get("mail_account_id") normalized["mail_account_id"] = ( str(mail_account_id).strip() if mail_account_id is not None and str(mail_account_id).strip() else None ) service_id = normalized.get("mail_service_id") normalized["mail_service_id"] = ( str(service_id).strip() if service_id is not None and str(service_id).strip() else None ) return normalized
23 unmodified lines return None
def add_account(email, password, cloudmail_account_id=None, seat_type=SEAT_UNKNOWN, workspace_account_id=None):def add_account( email, password, cloudmail_account_id=None, seat_type=SEAT_UNKNOWN, workspace_account_id=None, *, mail_provider=None, mail_account_id=None, mail_service_id=None,): """添加新账号。
seat_type 取值见 SEAT_CHATGPT / SEAT_CODEX / SEAT_UNKNOWN。11 unmodified lines patch["seat_type"] = seat_type if workspace_account_id and not existing.get("workspace_account_id"): patch["workspace_account_id"] = workspace_account_id if mail_provider and not existing.get("mail_provider"): patch["mail_provider"] = str(mail_provider).strip().lower() if mail_account_id is not None and not existing.get("mail_account_id"): patch["mail_account_id"] = str(mail_account_id).strip() if mail_service_id and not existing.get("mail_service_id"): patch["mail_service_id"] = str(mail_service_id).strip() if patch: update_account(email, **patch) return8 unmodified lines "email": email, "password": password, "cloudmail_account_id": cloudmail_account_id, "mail_provider": str(mail_provider or "").strip().lower(), "mail_account_id": ( str(mail_account_id).strip() if mail_account_id is not None and str(mail_account_id).strip() else None ), "mail_service_id": ( str(mail_service_id).strip() if mail_service_id is not None and str(mail_service_id).strip() else None ), "status": STATUS_PENDING, "seat_type": seat_type or SEAT_UNKNOWN, "workspace_account_id": workspace_account_id, # 邀请时所在的母号 workspace ID,母号切换检测用12 unmodified lines131415161718199 unmodified lines293031313233343536373839404142434445464748495051521 unmodified line54555657585960616232 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029113 unmodified lines305306307308309310311312313314315316317318319320321322323324325188 unmodified lines514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709348 unmodified lines10581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143510 unmodified lines144614471448144914501451145225 unmodified lines14781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115024 unmodified lines150715081509151015111512151315141515151615171 unmodified line15191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730131 unmodified lines18621863186485685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089118651866186718681869187018711872187318741875187618771878187918801881138 unmodified lines202020212022202320242025202620272028202920308 unmodified lines20392040204120422043204420452046204720482049205067 unmodified lines211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147246 unmodified lines2394239523961381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314042397239823992400240124022403240424052406240724082409265 unmodified lines2675267626772678267926802681268226832684268526862687268826892690269126922693201 unmodified lines28952896289718831884188518861887188828982899290029012902290329042905290629071890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196629082909291029112912339 unmodified lines325232533254325532563257325832591 unmodified line326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328517 unmodified lines33033304330533063307330833093310331133123313331433153316331733183319332033213322294 unmodified lines3617361836193620362136223623362486 unmodified lines37113712371327413714371537163717371837193720372137222748372337243725372637273728372937303731373237333734373537363737373837393740374137423743374412 unmodified linesfrom playwright.sync_api import sync_playwright
import autoteam.display # noqa: F401from autoteam import oauth_workspace as _oauth_workspacefrom autoteam.accounts import is_supported_plan, normalize_plan_typefrom autoteam.admin_state import ( get_admin_email,9 unmodified lines)from autoteam.playwright_lifecycle import close_playwright_objectsfrom autoteam.signup_profile import SignupProfile, generate_signup_profilefrom autoteam.textio import write_textfrom autoteam.textio import read_text, write_text
logger = logging.getLogger(__name__)
PROJECT_ROOT = Path(__file__).parent.parent.parentSCREENSHOT_DIR = PROJECT_ROOT / "screenshots"_OAUTH_TRACE_LIMIT = 40_OAUTH_TRACE_KEYWORDS = ( "/oauth/authorize", "/sign-in-with-chatgpt/codex", "choose-an-account", "consent", "organization", "email-verification", "log-in", "/auth/callback", "no_valid_organizations",)
# Codex OAuth 配置CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"1 unmodified lineCODEX_TOKEN_URL = "https://auth.openai.com/oauth/token"CODEX_CALLBACK_PORT = 1455CODEX_REDIRECT_URI = f"http://localhost:{CODEX_CALLBACK_PORT}/auth/callback"_OTP_REJECTION_FILE = AUTH_DIR / "otp_rejections.json"_OTP_REJECTION_TTL_SECONDS = 2 * 60 * 60_OTP_REJECTION_MAX_PER_EMAIL = 100
# SPEC-2 shared/quota-classification §4.4 I5 — Codex backend 最小推理端点(用于 uninitialized_seat 二次验证)_CODEX_SMOKE_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses"32 unmodified lines return {}
def _otp_rejection_email_key(email: str | None) -> str: return str(email or "").strip().lower()
def _otp_rejection_hash(email: str | None, code: str | None) -> str: key = f"{_otp_rejection_email_key(email)}:{str(code or '').strip()}" return hashlib.sha256(key.encode("utf-8")).hexdigest()
def _load_otp_rejection_store() -> dict: try: if not _OTP_REJECTION_FILE.exists(): return {} data = json.loads(read_text(_OTP_REJECTION_FILE)) return data if isinstance(data, dict) else {} except Exception as exc: logger.debug("[Codex] failed to load OTP rejection cache: %s", exc) return {}
def _write_otp_rejection_store(data: dict) -> None: try: ensure_auth_dir() write_text(_OTP_REJECTION_FILE, json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True)) ensure_auth_file_permissions(_OTP_REJECTION_FILE) except Exception as exc: logger.debug("[Codex] failed to write OTP rejection cache: %s", exc)
def _coerce_int(value): try: return int(value) except Exception: return None
def _load_recent_otp_rejections(email: str | None, *, now: float | None = None): now = time.time() if now is None else float(now) cutoff = now - _OTP_REJECTION_TTL_SECONDS key = _otp_rejection_email_key(email) data = _load_otp_rejection_store() records = data.get(key, []) if not isinstance(records, list): return set(), set()
code_hashes = set() email_ids = set() kept = [] changed = False for record in records: if not isinstance(record, dict): changed = True continue try: created_at = float(record.get("ts") or 0) except Exception: created_at = 0 if created_at and created_at < cutoff: changed = True continue code_hash = str(record.get("code_hash") or "").strip() if code_hash: code_hashes.add(code_hash) email_id = _coerce_int(record.get("email_id")) if email_id is not None: email_ids.add(email_id) kept.append(record)
if changed: if kept: data[key] = kept[-_OTP_REJECTION_MAX_PER_EMAIL:] else: data.pop(key, None) _write_otp_rejection_store(data)
return code_hashes, email_ids
def _record_otp_rejection(email: str | None, code: str | None, email_id, *, now: float | None = None): code = str(code or "").strip() if not code: return None
now = time.time() if now is None else float(now) cutoff = now - _OTP_REJECTION_TTL_SECONDS key = _otp_rejection_email_key(email) code_hash = _otp_rejection_hash(email, code) email_id_int = _coerce_int(email_id)
data = _load_otp_rejection_store() records = data.get(key, []) if not isinstance(records, list): records = []
kept = [] for record in records: if not isinstance(record, dict): continue try: created_at = float(record.get("ts") or 0) except Exception: created_at = 0 if created_at and created_at < cutoff: continue if str(record.get("code_hash") or "") == code_hash: continue if email_id_int is not None and _coerce_int(record.get("email_id")) == email_id_int: continue kept.append(record)
kept.append({"code_hash": code_hash, "email_id": email_id_int, "ts": now}) data[key] = kept[-_OTP_REJECTION_MAX_PER_EMAIL:] _write_otp_rejection_store(data) return code_hash
def _page_excerpt(page, limit=240) -> str: try: text = page.locator("body").inner_text(timeout=1500) text = re.sub(r"\s+", " ", text).strip() return text[:limit] except Exception: return ""
def _normalize_trace_text(value, limit=240) -> str: text = re.sub(r"\s+", " ", str(value or "")).strip() return text[:limit]
def _should_trace_oauth_network(url: str | None) -> bool: lowered = (url or "").lower() if "auth.openai.com" not in lowered and f"localhost:{CODEX_CALLBACK_PORT}" not in lowered: return False return any(keyword in lowered for keyword in _OAUTH_TRACE_KEYWORDS)
def _append_oauth_trace(trace_events: list[dict], *, kind: str, url: str, **fields) -> None: if not _should_trace_oauth_network(url): return
entry = {"kind": kind, "url": url} for key, value in fields.items(): if value is None: continue if key in {"body_excerpt", "location", "failure", "resource_type"}: entry[key] = _normalize_trace_text(value, limit=320) else: entry[key] = value
trace_events.append(entry) if len(trace_events) > _OAUTH_TRACE_LIMIT: del trace_events[:-_OAUTH_TRACE_LIMIT]
def _oauth_trace_has_login_challenge(trace_events: list[dict]) -> bool: for entry in trace_events[-12:]: for key in ("url", "location"): value = str(entry.get(key) or "").lower() if "/api/accounts/login" in value or "auth.openai.com/log-in" in value: return True return False
def _classify_oauth_failure(url: str | None, body_excerpt: str = ""): lowered_url = (url or "").lower() body = (body_excerpt or "").lower()
if "add-phone" in lowered_url: return "add_phone", "需要手机号验证", False if "verify you are human" in body or "captcha" in body: return "human_verification", "命中人机验证", False if "operation timed out" in body: return "oauth_timeout", "OAuth 授权页操作超时", True if "unsupported_country_region_territory" in body or "country, region, or territory not supported" in body: return "unsupported_region", "OAuth 授权接口返回不支持当前地区/出口", True if "choose-an-account" in lowered_url: return "account_selection", "停留在账号选择页", True if "no_valid_organizations" in body or "no valid organizations" in body: return "no_valid_organizations", "OAuth 授权页未选中可用 organization", True if "unable to load site" in body or "try again later" in body or "status page" in body: return "site_unavailable", "站点暂时不可用或代理异常", True if "email-verification" in lowered_url: return "email_verification", "卡在邮箱验证码页", True if "workspace" in lowered_url: return "workspace_selection", "卡在 workspace 选择页", True if "/auth/login" in lowered_url or "/log-in" in lowered_url or "log-in-or-create-account" in lowered_url: return "login_state_lost", "登录态丢失或回到了登录页", True return "auth_code_missing", f"未获取到 auth code(停留在 {lowered_url or 'unknown'})", True
def _screenshot(page, name): SCREENSHOT_DIR.mkdir(exist_ok=True) page.screenshot(path=str(SCREENSHOT_DIR / name), full_page=True)13 unmodified lines return f"{CODEX_AUTH_URL}?{urllib.parse.urlencode(params)}"
def _is_workspace_selection_page(page) -> bool: """Compatibility wrapper around the shared OAuth workspace detector.""" return _oauth_workspace._is_workspace_selection_page(page)
def _workspace_label_candidates(page): """Compatibility wrapper around shared workspace label extraction.""" return _oauth_workspace._workspace_label_candidates(page)
def _select_team_workspace(page, workspace_name: str) -> bool: """Compatibility wrapper around shared Team workspace selection.""" return _oauth_workspace._select_team_workspace(page, workspace_name)
def _exchange_auth_code(auth_code, code_verifier, fallback_email=None): logger.info("[Codex] 获取到 auth code,交换 token...")
188 unmodified lines return access_token
def _bundle_from_access_token(access_token, email, account_id): claims = _parse_jwt_payload(access_token) auth_claims = claims.get("https://api.openai.com/auth", {}) raw_plan = auth_claims.get("chatgpt_plan_type", "unknown") resolved_email = claims.get("email", email or "") resolved_account_id = account_id or auth_claims.get("chatgpt_account_id", "") return { "access_token": access_token, "refresh_token": "", "id_token": access_token, "account_id": resolved_account_id, "email": resolved_email, "plan_type": normalize_plan_type(raw_plan), "plan_type_raw": raw_plan, "plan_supported": is_supported_plan(raw_plan), "expired": time.time() + 3600, }
def _bundle_from_session_token(session_token, email, account_id): return _bundle_from_access_token(session_token, email, account_id)
def _oauth_result_from_bundle(bundle): return { "ok": True, "bundle": bundle, "error_type": None, "error_detail": None, "retryable": False, }
def _inject_team_account_cookies(context, account_id: str | None) -> None: account_id = (account_id or "").strip() if not account_id: return try: context.add_cookies( [ { "name": "_account", "value": account_id, "domain": "chatgpt.com", "path": "/", "secure": True, "sameSite": "Lax", }, { "name": "_account", "value": account_id, "domain": "auth.openai.com", "path": "/", "secure": True, "sameSite": "Lax", }, ] ) except Exception as exc: logger.debug("[Codex-Fallback] 注入 Team account cookie 失败: %s", exc)
def _is_valid_team_access_token(access_token: str | None, account_id: str | None) -> bool: if not access_token: return False claims = _parse_jwt_payload(access_token) auth_claims = claims.get("https://api.openai.com/auth", {}) plan_type = normalize_plan_type(auth_claims.get("chatgpt_plan_type", "")) token_account_id = str(auth_claims.get("chatgpt_account_id") or "").strip() expected_account_id = str(account_id or "").strip() if expected_account_id and token_account_id and token_account_id != expected_account_id: return False return plan_type == "team"
def _session_token_supports_team_quota(page, session_token, account_id): try: result = page.evaluate( """async ([teamAccountId, token]) => { try { const resp = await fetch("/backend-api/wham/usage", { credentials: "include", headers: { "Accept": "application/json", "Authorization": `Bearer ${token || ""}`, }, }); const text = await resp.text().catch(() => ""); return { status: resp.status, body: text }; } catch (e) { return { status: 0, body: String(e && e.message || e) }; } }""", [account_id, session_token], ) except Exception as exc: logger.info("[Codex-Fallback] Team quota probe exception: %s", exc) return False
status = result.get("status") if isinstance(result, dict) else None if status == 200: return True logger.info( "[Codex-Fallback] Team quota probe rejected session token: status=%s body=%s", status, (result or {}).get("body", "") if isinstance(result, dict) else "", ) return False
def _fetch_team_session_bundle_from_context( context, email: str, account_id: str | None, *, stage_label: str, attempts: int = 3,) -> dict | None: """Use an already logged-in ChatGPT session as Codex auth material."""
account_id = (account_id or "").strip() page = None try: _inject_team_account_cookies(context, account_id) page = context.new_page() target_url = f"https://chatgpt.com/admin/workspace/{account_id}" if account_id else "https://chatgpt.com/" page.goto(target_url, wait_until="domcontentloaded", timeout=30000) time.sleep(2)
for attempt in range(1, max(1, attempts) + 1): session = page.evaluate( """async () => { try { const resp = await fetch("/api/auth/session"); return await resp.json(); } catch (e) { return { error: String(e && e.message || e) }; } }""" ) token = session.get("accessToken") if isinstance(session, dict) else None if _is_valid_team_access_token(token, account_id): bundle = _bundle_from_access_token(token, email, account_id) logger.info( "[Codex-Fallback] %s 获取到 ChatGPT Team session token: email=%s plan=%s", stage_label, bundle.get("email") or email, bundle.get("plan_type"), ) return bundle
if token and _session_token_supports_team_quota(page, token, account_id): bundle = _bundle_from_session_token(token, email, account_id) bundle["plan_type"] = "team" bundle["plan_supported"] = True logger.info( "[Codex-Fallback] %s JWT claims 未切到 Team,但 wham/usage 已验证目标 Team 可用: email=%s account=%s", stage_label, bundle.get("email") or email, account_id, ) return bundle
if token: claims = _parse_jwt_payload(token) auth_claims = claims.get("https://api.openai.com/auth", {}) logger.info( "[Codex-Fallback] %s session token 不匹配 Team workspace (attempt %d/%d): account=%s plan=%s", stage_label, attempt, attempts, auth_claims.get("chatgpt_account_id"), auth_claims.get("chatgpt_plan_type"), )
if attempt < attempts: page.reload(wait_until="domcontentloaded", timeout=30000) time.sleep(1) return None except Exception as exc: logger.warning("[Codex-Fallback] %s session bundle 提取失败: %s", stage_label, exc) return None finally: if page is not None: try: page.close() except Exception: pass
def fetch_personal_uuid(access_token): """Round 11 V8 — POST https://chatgpt.com/backend-api/accounts/personal idempotent getOrCreate.
348 unmodified lines return False
def _select_existing_api_organization(page) -> bool: trigger_selectors = ( 'button:has-text("New organization")', '[role="button"]:has-text("New organization")', 'button:has-text("新组织")', '[role="button"]:has-text("新组织")', )
for selector in trigger_selectors: try: trigger = page.locator(selector).first if not trigger.is_visible(timeout=800): continue
trigger.click() time.sleep(0.5) for option in page.locator('[role="option"]').all(): try: label = option.inner_text(timeout=500).strip() except Exception: continue lowered = label.lower() if not label or "new organization" in lowered or "新组织" in label: continue option.click() logger.info("[Codex] 已切换到已有 API organization: %s", label) time.sleep(0.5) return True
logger.warning("[Codex] API organization 下拉中未找到可用的已有组织,保留当前选择") return False except Exception: continue
return False
_CHOOSE_ACCOUNT_PAGE_HINTS = ( "choose an account", "select an account", "continue as", "choose a chatgpt account", "选择一个账号", "选择账号",)_CHOOSE_ACCOUNT_IGNORE_LABELS = { "choose an account", "select an account", "choose a chatgpt account", "continue as", "continue", "继续", "allow", "log in", "cancel", "back", "terms of use", "privacy policy",}_CHOOSE_ACCOUNT_IGNORE_SUBSTRINGS = ( "terms of use", "privacy policy", "continue with",)
def _is_choose_account_page(page) -> bool: url = (getattr(page, "url", "") or "").lower() if "choose-an-account" in url: return True
try: body = page.locator("body").inner_text(timeout=1200).lower() except Exception: body = ""
return any(hint in body for hint in _CHOOSE_ACCOUNT_PAGE_HINTS)
def _is_choose_account_ignored_label(text: str) -> bool: lowered = str(text or "").strip().lower() if lowered in _CHOOSE_ACCOUNT_IGNORE_LABELS: return True return any(token in lowered for token in _CHOOSE_ACCOUNT_IGNORE_SUBSTRINGS)
def _click_oauth_locator(loc) -> bool: try: loc.click(timeout=3000) return True except Exception: try: loc.click(force=True) return True except Exception: return False
def _choose_account_label_candidates(page): if not _is_choose_account_page(page): return []
selectors = ( "button", "a", '[role="button"]', '[role="option"]', '[aria-selected="true"]', '[aria-selected="false"]', "[data-state]", "li", "label", "div", ) seen = set() candidates = [] for selector in selectors: try: for loc in page.locator(selector).all(): try: if not loc.is_visible(timeout=100): continue text = re.sub(r"\s+", " ", loc.inner_text(timeout=200)).strip() except Exception: continue lowered = text.lower() if not text or lowered in seen or len(text) > 160 or _is_choose_account_ignored_label(lowered): continue seen.add(lowered) candidates.append((text, loc)) except Exception: continue return candidates
def _select_oauth_account(page, email: str | None) -> bool: preferred_email = str(email or "").strip().lower() if not preferred_email: return False local_part = preferred_email.split("@", 1)[0] if "@" in preferred_email else preferred_email
for text, loc in _choose_account_label_candidates(page): lowered = text.strip().lower() if preferred_email not in lowered and (not local_part or local_part not in lowered): continue if not _click_oauth_locator(loc): continue logger.info("[Codex] 选择 OAuth 账号: %s", text) time.sleep(2) try: confirm = page.locator( 'button:has-text("Continue"), button:has-text("继续"), button:has-text("Allow")' ).first if confirm.is_visible(timeout=800): confirm.click() logger.info("[Codex] 已确认 OAuth 账号选择") time.sleep(3) except Exception: pass return True
for selector in ( f'text="{preferred_email}"', f"text=/{re.escape(preferred_email)}/i", ): try: loc = page.locator(selector).first if not loc.is_visible(timeout=500): continue if not _click_oauth_locator(loc): continue logger.info("[Codex] 选择 OAuth 账号: %s", preferred_email) time.sleep(2) return True except Exception: continue
return False
def _select_choose_account(page, email: str | None) -> bool: return _select_oauth_account(page, email)
def _oauth_page_has_terminal_error(page) -> bool: body_excerpt = _page_excerpt(page, limit=400).lower() return ( "no_valid_organizations" in body_excerpt or "an error occurred during authentication" in body_excerpt or "operation timed out" in body_excerpt or "unsupported_country_region_territory" in body_excerpt or "country, region, or territory not supported" in body_excerpt )
def _recover_oauth_timeout_page(page) -> bool: body_excerpt = _page_excerpt(page, limit=400).lower() if "operation timed out" not in body_excerpt: return False
for selector in ( 'button:has-text("Try again")', '[role="button"]:has-text("Try again")', 'a:has-text("Try again")', 'button:has-text("Retry")', ): try: btn = page.locator(selector).first if not btn.is_visible(timeout=800): continue logger.info("[Codex] 命中 OAuth 超时错误页,尝试点击 Try again 继续当前流程...") btn.click() time.sleep(3) return True except Exception: continue
return False
def _recover_oauth_no_valid_organizations_page(page) -> bool: body_excerpt = _page_excerpt(page, limit=500).lower() if "no_valid_organizations" not in body_excerpt and "no valid organizations" not in body_excerpt: return False
for selector in ( 'button:has-text("Try again")', '[role="button"]:has-text("Try again")', 'a:has-text("Try again")', 'button:has-text("Retry")', '[role="button"]:has-text("Retry")', ): try: btn = page.locator(selector).first if not btn.is_visible(timeout=800): continue logger.info("[Codex] 命中 no_valid_organizations 错误页,尝试点击 Try again 继续当前 OAuth 流程...") btn.click() time.sleep(4) return True except Exception: continue
return False
def _is_oauth_login_challenge_page(page, trace_events=None) -> bool: try: url = (page.url or "").lower() except Exception: url = "" if "/api/accounts/login" in url or "auth.openai.com/log-in" in url: return True return bool(trace_events and _oauth_trace_has_login_challenge(trace_events) and "/oauth" not in url)
def _is_login_page_url(url: str | None) -> bool: url = (url or "").lower() return "/api/accounts/login" in url or "auth.openai.com/log-in" in url or "log-in-or-create-account" in url
def _wait_for_oauth_challenge_progress(page, timeout=20) -> bool: deadline = time.time() + timeout last_url = "" while time.time() < deadline: try: url = page.url or "" last_url = url except Exception: url = ""
lower_url = url.lower() if f"localhost:{CODEX_CALLBACK_PORT}/auth/callback" in lower_url: return True if ( lower_url and "/api/accounts/login" not in lower_url and "auth.openai.com/log-in" not in lower_url and "email-verification" not in lower_url ): if any(marker in lower_url for marker in ("/oauth", "consent", "organization", "choose-an-account")): return True
try: if _is_otp_input_visible(page, timeout=300): return False except Exception: pass
time.sleep(0.5)
logger.info("[Codex] OAuth login challenge progress wait timed out, last_url=%s", last_url) return False
def _complete_oauth_login_challenge(page, email, password, mail_client, min_email_id, used_email_ids) -> bool: acted = False
try: for attempt in range(2): email_input = page.locator('input[name="email"], input[id="email-input"], input[id="email"]').first if not email_input.is_visible(timeout=3000): break email_input.fill(email) acted = True time.sleep(0.5) _click_primary_auth_button(page, email_input, ["Continue", "继续"]) time.sleep(3) if not _is_google_redirect(page): break _screenshot(page, f"codex_login_challenge_google_email_{attempt + 1}.png") logger.warning("[Codex] OAuth login challenge email step redirected to Google; retrying") page.go_back(wait_until="domcontentloaded", timeout=30000) time.sleep(2) except Exception: pass
try: for attempt in range(2): pwd_input = page.locator('input[name="password"], input[type="password"]').first if not pwd_input.is_visible(timeout=3000): break acted = True if password: pwd_input.fill(password) time.sleep(0.5) _click_primary_auth_button(page, pwd_input, ["Continue", "继续", "Log in"]) else: otp_btn = page.locator( 'button:has-text("一次性验证码"), button:has-text("one-time"), button:has-text("email login")' ).first if otp_btn.is_visible(timeout=3000): otp_btn.click() else: _click_primary_auth_button(page, pwd_input, ["Continue", "继续", "Log in"]) time.sleep(5) if not _is_google_redirect(page): break _screenshot(page, f"codex_login_challenge_google_password_{attempt + 1}.png") logger.warning("[Codex] OAuth login challenge password step redirected to Google; retrying") page.go_back(wait_until="domcontentloaded", timeout=30000) time.sleep(2) except Exception: pass
try: if _is_otp_input_visible(page, timeout=3000): if not mail_client: logger.warning("[Codex] OAuth login challenge needs OTP but no mail_client is available") return acted submit_status = _resolve_email_verification( page, mail_client=mail_client, email=email, after_email_id=min_email_id, used_email_ids=used_email_ids, wait_log="[Codex] OAuth login challenge needs OTP, waiting for emailId > %d", wait_timeout=90, ) if submit_status != "no_code": acted = True _wait_for_oauth_challenge_progress(page, timeout=20) except Exception: pass
if "about-you" in (page.url or ""): _complete_oauth_about_you(page) acted = True
return acted
def _is_google_redirect(page): url = (page.url or "").lower() if "accounts.google.com" in url:10 unmodified lines 'input[name="code"], input[inputmode="numeric"], input[autocomplete="one-time-code"], ' 'input[placeholder*="验证码"], input[placeholder*="code" i]')_OTP_SINGLE_INPUT_SELECTORS = 'input[maxlength="1"], input[data-input-otp], input[aria-label*="digit" i]'_OTP_INVALID_HINTS = ( "invalid code", "incorrect code",25 unmodified lines return None
def _is_otp_progress_url(url: str | None) -> bool: url = (url or "").lower() if not url: return False if f"localhost:{CODEX_CALLBACK_PORT}/auth/callback" in url: return True return any( marker in url for marker in ( "consent", "organization", "choose-an-account", "about-you", "/oauth/oauth2/auth", "/sign-in-with-chatgpt/codex", ) ) and "email-verification" not in url
def _wait_for_otp_submit_result(page, timeout=12): """ 等待验证码提交结果:4 unmodified lines deadline = time.time() + timeout
while time.time() < deadline: try: if _is_otp_progress_url(page.url): return "accepted", None except Exception: pass err = _detect_otp_error(page) if err: return "invalid", err1 unmodified line return "accepted", None time.sleep(0.5)
try: if _is_otp_progress_url(page.url): return "accepted", None except Exception: pass err = _detect_otp_error(page) if err: return "invalid", err return "pending", None
def _visible_otp_slot_inputs(page, timeout=300): try: candidates = page.locator(_OTP_SINGLE_INPUT_SELECTORS).all() except Exception: return []
visible = [] for loc in candidates: try: if loc.is_visible(timeout=timeout): visible.append(loc) except Exception: continue return visible
def _fill_otp_code(page, code: str) -> bool: value = str(code or "").strip() if not value: return False
slot_inputs = _visible_otp_slot_inputs(page, timeout=200) if len(slot_inputs) >= min(4, len(value)): logger.info("[Codex] 检测到 %d 个单字符验证码输入框", len(slot_inputs)) for index, char in enumerate(value): if index >= len(slot_inputs): break loc = slot_inputs[index] try: loc.click(force=True) except Exception: pass try: loc.fill("") except Exception: pass try: loc.fill(char) except Exception: try: loc.type(char, delay=50) except Exception: try: page.keyboard.type(char, delay=50) except Exception: return False time.sleep(0.1) return True
try: otp_input = page.locator(_OTP_INPUT_SELECTORS).first if otp_input.is_visible(timeout=2000): otp_input.fill(value) return True except Exception: pass
return False
def _click_otp_submit_button(page) -> bool: for selector in ( 'button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("继续")', 'button:has-text("Verify")', ): try: button = page.locator(selector).first if button.is_visible(timeout=800): button.click() return True except Exception: continue return False
def _poll_mail_verification_code( mail_client, email: str, *, after_email_id: int, used_email_ids: set[int], timeout: int = 120, require_sender: bool = False,): deadline = time.time() + timeout while time.time() < deadline: for em in mail_client.search_emails_by_recipient(email, size=5): email_id = em.get("emailId", 0) if email_id <= after_email_id or email_id in used_email_ids: continue
if require_sender: sender = (em.get("sendEmail") or "").lower() if "openai" not in sender and "chatgpt" not in sender: continue
subject = (em.get("subject") or "").lower() if "invited" in subject or "invitation" in subject: continue
code = mail_client.extract_verification_code(em) if code: return code, email_id time.sleep(3)
return None, 0
def _resolve_email_verification( page, *, mail_client, email: str, after_email_id: int, used_email_ids: set[int], wait_log: str, require_sender: bool = False, wait_timeout: int = 120, submit_timeout: int = 15,) -> str: logger.info(wait_log, after_email_id)
otp, otp_email_id = _poll_mail_verification_code( mail_client, email, after_email_id=after_email_id, used_email_ids=used_email_ids, timeout=wait_timeout, require_sender=require_sender, ) if not otp: logger.warning("[Codex] 未获取到验证码") return "no_code"
logger.info("[Codex] 获取到验���码: %s", otp)
for submit_attempt in range(1, 3): current_url = (getattr(page, "url", "") or "").lower() if current_url and "email-verification" not in current_url: used_email_ids.add(otp_email_id) return "accepted"
if not _fill_otp_code(page, otp): if current_url and "email-verification" not in current_url: used_email_ids.add(otp_email_id) return "accepted" if submit_attempt < 2: logger.warning("[Codex] 验证码输入框不可用,准备重试第 %d/2 次", submit_attempt + 1) time.sleep(2) continue used_email_ids.add(otp_email_id) logger.warning("[Codex] 验证码输入框不可用,标记并跳过邮件 %s", otp_email_id) return "input_unavailable"
time.sleep(0.5) _click_otp_submit_button(page) logger.info("[Codex] 已输入验证码: %s", otp)
submit_status, submit_detail = _wait_for_otp_submit_result(page, timeout=submit_timeout) if submit_status == "accepted": used_email_ids.add(otp_email_id) return "accepted" if 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, ) return "invalid"
if 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, ) return "pending"
return "pending"
def _typewrite_credential(page, locator, value, *, delay_ms=50, post_sleep=1.0): """逐字符 keyboard.type 填入 credential,触发 React onChange 事件链.
131 unmodified lines
# === 可能 OTP === try: ci = page.locator(_OTP_INPUT_SELECTORS).first if ci.is_visible(timeout=5000) and mail_client: logger.info("[Codex] fresh re-login: 需要 OTP,等待 emailId > %d 的新邮件...", fresh_email_id_before) otp = None otp_email_id = 0 t0 = time.time() while time.time() - t0 < 120: for em in mail_client.search_emails_by_recipient(email, size=5): eid = em.get("emailId", 0) if eid <= fresh_email_id_before or eid in used_email_ids: continue sender = (em.get("sendEmail") or "").lower() if "openai" not in sender and "chatgpt" not in sender: continue subj = (em.get("subject") or "").lower() if "invited" in subj or "invitation" in subj: continue otp = mail_client.extract_verification_code(em) if otp: otp_email_id = eid break if otp: break time.sleep(3) if otp: used_email_ids.add(otp_email_id) logger.info("[Codex] fresh re-login: 获取到 OTP %s", otp) ci.fill(otp) time.sleep(0.5) page.locator( 'button[type="submit"], button:has-text("Continue"), button:has-text("继续")' ).first.click() time.sleep(5) _screenshot(page, "codex_relogin_04_after_otp.png") else: logger.warning("[Codex] fresh re-login: 未获取到 OTP") if _is_otp_input_visible(page, timeout=5000) and mail_client: _resolve_email_verification( page, mail_client=mail_client, email=email, after_email_id=fresh_email_id_before, used_email_ids=used_email_ids, wait_log="[Codex] fresh re-login: 需要 OTP,等待 emailId > %d 的新邮件...", require_sender=True, ) time.sleep(5) _screenshot(page, "codex_relogin_04_after_otp.png") elif _is_otp_input_visible(page, timeout=500): logger.warning("[Codex] fresh re-login: 需要 OTP 但无 mail_client") except Exception: pass
138 unmodified lines password, mail_client=None, *, return_result=False, use_personal=False, chatgpt_session_token=None, prefetched_personal_uuid=None, pre_signed_in_cookies: list | None = None, signup_profile: SignupProfile | None = None, playwright_proxy_url: str | None = None,):8 unmodified lines prefetched_personal_uuid: Round 11 V8 — accounts.json 持久化的 personal_workspace_id; 非空时直接拼到 OAuth `auth_url` 的 allowed_workspace_id 参数, 省一次 silent step-0 内的 POST /accounts/personal。 pre_signed_in_cookies: 直接注册后传入的已登录 chatgpt.com/auth.openai.com cookies。 提供时优先尝试 ChatGPT session fallback,避免新号二次 OAuth 登录挑战。 signup_profile: 注册 about-you 使用过的身份快照;OAuth about-you 必须复用它。 返回 auth bundle: {access_token, refresh_token, id_token, account_id, email, plan_type, personal_workspace_id} return_result=True 时返回 {ok, bundle, error_type, error_detail, retryable}。
Round 11 五轮 Option A — 两阶段 personal OAuth: 阶段 1(快路径):有 chatgpt_session_token → silent step-0 双域注入 + NextAuth refresh,67 unmodified lines browser = p.chromium.launch(**launch_kwargs) context = browser.new_context(**get_playwright_context_options())
if pre_signed_in_cookies: try: context.add_cookies(pre_signed_in_cookies) logger.info( "[Codex] 已注入 %d 个 session cookie,优先尝试 ChatGPT session fallback", len(pre_signed_in_cookies), ) except Exception as exc: logger.warning("[Codex] 注入 session cookie 失败,回退到完整登录: %s", exc) pre_signed_in_cookies = None
if pre_signed_in_cookies and not use_personal: session_fallback_bundle = _fetch_team_session_bundle_from_context( context, email, chatgpt_account_id, stage_label="pre-oauth", ) if session_fallback_bundle: close_playwright_objects(context=context, browser=browser, logger=logger, label="codex-session-fallback") if return_result: return _oauth_result_from_bundle(session_fallback_bundle) return session_fallback_bundle
# Round 11 四轮 — Personal 模式 session_token 注入(silent step-0): # 实测刚踢出 Team 的新号在 OAuth /log-in 页 fill email 后 Continue 按钮变灰禁用, # login flow 永远卡在 email 步骤,bundle=None。根因疑似 Playwright fill() 的246 unmodified lines
# 可能需要邮箱验证码 try: ci = _page.locator('input[name="code"]').first if ci.is_visible(timeout=5000) and mail_client: logger.info("[Codex] ChatGPT 登录需要验证码,等待 emailId > %d 的新邮件...", _email_id_before_login) otp = None otp_email_id = 0 t0 = 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) if email_id <= _email_id_before_login or email_id in _used_email_ids: continue otp = mail_client.extract_verification_code(em) if otp: otp_email_id = email_id break if otp: break time.sleep(3) if otp: _used_email_ids.add(otp_email_id) ci.fill(otp) time.sleep(0.5) _page.locator('button[type="submit"]').first.click() time.sleep(5) if mail_client and _is_otp_input_visible(_page, timeout=5000): _resolve_email_verification( _page, mail_client=mail_client, email=email, after_email_id=_email_id_before_login, used_email_ids=_used_email_ids, wait_log="[Codex] ChatGPT 登录需要验证码,等待 emailId > %d ���新邮件...", ) time.sleep(5) except Exception: pass
265 unmodified lines
_screenshot(page, f"codex_04_step{step + 1}_before.png")
try: if _is_choose_account_page(page): _screenshot(page, f"codex_04_choose_account_{step + 1}_before.png") logger.info("[Codex] 检测到账号选择页 (step %d),尝试选择: %s", step + 1, email) selected = _select_oauth_account(page, email) _screenshot(page, f"codex_04_choose_account_{step + 1}_after.png") if selected and not _is_choose_account_page(page): continue if not selected: logger.warning("[Codex] 无法自动选择 OAuth 账号: %s (step %d)", email, step + 1) except Exception: pass
# 在任何页面中,如果有 workspace/组织选择,先选 Team(personal 模式下选个人) try: # Round 11 — 与 cnitlrt/AutoTeam upstream codex_auth.py:772-815 对齐:201 unmodified lines
# 处理邮箱验证码页面(可能在 consent 流程中出现) try: otp_input = page.locator(_OTP_INPUT_SELECTORS).first if otp_input.is_visible(timeout=2000) and mail_client: logger.info( "[Codex] 需要邮箱验证码 (step %d),等待 emailId > %d 的新邮件...", step + 1, _email_id_before_login, if _is_otp_input_visible(page, timeout=2000) and mail_client: submit_status = _resolve_email_verification( page, mail_client=mail_client, email=email, after_email_id=_email_id_before_login, used_email_ids=_used_email_ids, wait_log=f"[Codex] 需要邮箱验证码 (step {step + 1}),等待 emailId > %d 的新邮件...", require_sender=True, ) otp = None otp_email_id = 0 page_left_code = False t0 = time.time() while time.time() - t0 < 120: if not _is_otp_input_visible(page, timeout=300): page_left_code = True logger.info("[Codex] 验证码页已退出,继续后续授权流程") break for em in mail_client.search_emails_by_recipient(email, size=5): # 只接受比快照更新的邮件 email_id = em.get("emailId", 0) if email_id <= _email_id_before_login or email_id in _used_email_ids: continue sender = (em.get("sendEmail") or "").lower() if "openai" not in sender and "chatgpt" not in sender: continue subj = (em.get("subject") or "").lower() if "invited" in subj or "invitation" in subj: continue otp = mail_client.extract_verification_code(em) if otp: otp_email_id = email_id break if otp: break time.sleep(3) if otp: submit_ok = False for submit_attempt in range(1, 3): otp_input = page.locator(_OTP_INPUT_SELECTORS).first if not otp_input.is_visible(timeout=2000): submit_ok = True break
otp_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 = True break if 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, ) break
if 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) continue if page_left_code: if submit_status == "accepted": logger.info("[Codex] 验证码页已退出,继续后续授权流程") continue except Exception: pass339 unmodified lines
if personal_uuid: stage2_bundle["personal_workspace_id"] = personal_uuid if return_result: return _oauth_result_from_bundle(stage2_bundle) return stage2_bundle
# 阶段 1 通过(非 personal 或 plan == free) — 走原退出路径1 unmodified line
if not auth_code: logger.error("[Codex] OAuth 登录失败: 未获取到 authorization code") if return_result: return { "ok": False, "bundle": None, "error_type": "auth_code_missing", "error_detail": "未获取到 authorization code", "retryable": True, } return None
if not stage1_bundle: if return_result: return { "ok": False, "bundle": None, "error_type": "token_exchange_failed", "error_detail": "Token 交换失败", "retryable": True, } return None
# Personal 模式强校验 plan_type:当子号还挂在 Team workspace(OpenAI 后端 kick 同步延迟 /17 unmodified lines plan or "unknown", stage1_bundle.get("account_id"), ) if return_result: return { "ok": False, "bundle": None, "error_type": "non_free_plan", "error_detail": f"personal OAuth plan={plan or 'unknown'}", "retryable": True, } return None
if personal_uuid: stage1_bundle["personal_workspace_id"] = personal_uuid if return_result: return _oauth_result_from_bundle(stage1_bundle) return stage1_bundle
294 unmodified lines if step == "password_required": if self._switch_password_to_otp(): continue if self._auto_fill_password(): continue return { "step": "unsupported_password", "detail": "主号 Codex 当前停留在密码页,且未找到一次性验证码入口",86 unmodified lines self.page = None
class MainCodexSyncFlow(SessionCodexAuthFlow):class MainCodexLoginFlow(SessionCodexAuthFlow): def __init__(self): from autoteam.admin_state import get_admin_password
super().__init__( email=get_admin_email(), session_token=get_admin_session_token(), account_id=get_chatgpt_account_id(), workspace_name=get_chatgpt_workspace_name(), password="", password=get_admin_password(), password_callback=None, auth_file_callback=save_main_auth_file, )
def complete(self): info = super().complete() return { "email": info.get("email"), "auth_file": info.get("auth_file"), "plan_type": info.get("plan_type"), }
class MainCodexSyncFlow(MainCodexLoginFlow): def complete(self): info = super().complete() from autoteam.sync_targets import sync_main_codex_to_configured_targets as sync_main_codex_to_cpa
sync_main_codex_to_cpa(info["auth_file"]) return { "email": info.get("email"),422 unmodified lines423424425426427428429143 unmodified lines5735745755765775785795805815825835845855865875881 unmodified line59059159258559359459559613 unmodified lines61061161261361461561674 unmodified lines6916926936946956966976986997 unmodified lines70770870971071171271371471571671771871972072172272372472597 unmodified lines823824825826827828829830831832833422 unmodified lines save_accounts, update_account, ) from autoteam.mail import infer_mail_provider_from_email
AUTH_DIR.mkdir(exist_ok=True)
143 unmodified lines
acc = find_account(accounts, email) resolved_path = str(normalized_path.resolve()) inferred_provider = infer_mail_provider_from_email(email) if acc: acc_changed = False if acc.get("auth_file") != resolved_path: acc["auth_file"] = resolved_path acc_changed = True if inferred_provider and not acc.get("mail_provider"): acc["mail_provider"] = inferred_provider acc_changed = True if acc_changed: changed_accounts = True updated_accounts += 1 else:1 unmodified line # 紧接着 update_account → STANDBY 一次性带上 auth_file. 这样状态机能落每条 # state_log.jsonl + F2 SSE 推送, 不再静默直 append 旁路. try: add_account(email, "", cloudmail_account_id=None) add_account(email, "", cloudmail_account_id=None, mail_provider=inferred_provider or None) update_account( email, status=STATUS_STANDBY,13 unmodified lines "email": email, "password": "", "cloudmail_account_id": None, "mail_provider": inferred_provider or "", "status": STATUS_STANDBY, "auth_file": resolved_path, "quota_exhausted_at": None,74 unmodified lines synced_active = 0 synced_personal = 0 disabled_skipped = 0 active_publish_skipped = 0 active_publish_kept_remote = 0 active_publish_delete_remote = 0 for acc in accounts: if is_account_disabled(acc): disabled_skipped += 17 unmodified lines path = Path(auth_path) if not path.exists(): continue
if status == STATUS_ACTIVE: decision = _active_auth_publish_decision(acc, path) if decision == "keep_remote": active_publish_kept_remote += 1 continue if decision == "delete_remote": active_publish_delete_remote += 1 continue if decision != "publish": active_publish_skipped += 1 continue
_refresh_account_proxy_url_for_upload(acc, path) files_to_sync[path.name] = path if status == STATUS_ACTIVE:97 unmodified lines "synced_active": synced_active, "synced_personal": synced_personal, "disabled_skipped": disabled_skipped, "active_publish": { "skipped_unknown": active_publish_skipped, "kept_remote": active_publish_kept_remote, "delete_remote": active_publish_delete_remote, }, "local_duplicates_deleted": local_duplicates_deleted, "delete_guard": { "allow_remote_delete": allow_remote_delete,29 unmodified lines3031323334353623 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293949596979829 unmodified lines "Email", "MailProvider", "get_mail_client", "infer_mail_provider_from_email",]
23 unmodified lines )
def _email_domain(value: object | None) -> str: text = str(value or "").strip().lower() if "@" not in text: return "" return text.rsplit("@", 1)[-1].lstrip("@").strip()
def _normalized_domain(value: object | None) -> str: return str(value or "").strip().lower().lstrip("@")
def infer_mail_provider_from_email(email: object | None, env: dict[str, object] | None = None) -> str: """Infer the configured mail provider from an account email domain.
The result is conservative: ambiguous or unknown domains return an empty string so account routing can fall back to the default provider. """ domain = _email_domain(email) if not domain: return ""
source = env or os.environ candidates: list[tuple[str, str]] = [ ("cf_temp_email", _normalized_domain(source.get("CLOUDMAIL_DOMAIN"))), ("maillab", _normalized_domain(source.get("MAILLAB_DOMAIN") or source.get("CLOUDMAIL_DOMAIN"))), ("addy_io", _normalized_domain(source.get("ADDY_IO_DOMAIN"))), ] matches = [provider for provider, provider_domain in candidates if provider_domain and provider_domain == domain] if len(set(matches)) == 1: return matches[0] return ""
def _build_chain_from_env(chain_env: str) -> MailProvider: """解析 MAIL_PROVIDER_CHAIN 字符串,返回 FallbackMailProvider。""" from autoteam.mail.fallback import FallbackMailProvider32 unmodified lines33343536373839136 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020151 unmodified lines25325425523525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733816 unmodified lines35535635735835936036136236336436536636736836937037137237337437537637753 unmodified lines431432433434435436437438439440441442443444445446447448449450451452453454455239 unmodified lines6956966976986997007017027037047057064 unmodified lines711712713714715716717718719720721722723724725726727100 unmodified lines82882983083183283383483583683783883984031 unmodified lines8728738748758768778788798808818828838848858868878888898907 unmodified lines89889990090190290390490590690790890991091113 unmodified lines9259269279289299309319329339349359369371 unmodified line93994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106838 unmodified lines1107110811097998008018028038048051110111111121113111411151116455 unmodified lines15721573157412671575157615771578157915801581158215831584158515861587158815891590159115921593136 unmodified lines17301731173214191420142114221423142414251426142714281429143014311733173417351736173717381739174017411742174317441745174617471748174917501751188 unmodified lines1940194119421626194319441945194619471948194919501951195219531954195516331956195719581959128 unmodified lines2088208920901768209120922093209420952096209720982099210021012102210321042105210621072108210921101774211121122113177717782114211521162117211821192120212121222123212421252126212721282129213021312132213321342135178221362137213821394 unmodified lines21442145214621472148214921508 unmodified lines215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021816 unmodified lines2188218921902191219221932194219521962197219821992200220122022203220422053 unmodified lines220922102211221222132214221556 unmodified lines2272227322742275227622772278189022792280228122822283228422852286189218931894228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623271896232823291898233023312332233327 unmodified lines2361236223631932193319342364236523662367236823692370237123722373237423751940194119421943194419451946237623772378237923802381238223832384238523862387238823 unmodified lines241224132414241524162417241824192420242124221983198424232424242524262427242824292430243124322433243424352436243724382439198619872440244124422443244424452446244724482449245024512452245324542455978 unmodified lines34343435343634373438343934403441344234433444143 unmodified lines358835893590312135913592359335943595359635973598359935 unmodified lines3635363636373638363936403641364236 unmodified lines36793680368132053682368336843685368636873688368936903691369236933694369536963207320832093210321136973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803115 unmodified lines3919392039213922392339243925392639 unmodified lines39663967396839693970397139723973291 unmodified lines426542664267426842694270427142724273427442754276427742788 unmodified lines4287428842893694429042914292429342944295429642974298429943004301430243034304430542 unmodified lines434843494350435143524353435443554356435743584359436043615 unmodified lines436743684369375837593760376137623763376443704371437243734374437543764377437843794380438143824383438443854386438743884389439043913766439243934394439511 unmodified lines440744084409378437853786378744104411441244134414513 unmodified lines4928492949304307493149324933493449354936493749384939494049412214 unmodified lines715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224116 unmodified lines734173427343734473457346734750 unmodified lines7398739974007401740274037404740532 unmodified linesfrom autoteam.accounts import ( STATUS_ACTIVE, STATUS_AUTH_INVALID, STATUS_AUTH_PENDING, STATUS_EXHAUSTED, STATUS_ORPHAN, STATUS_PENDING,136 unmodified lines
# 失败类型常量(上游 `.upstream/manager.py:96`)。Hard failure → 立即暂停 + 释放席位。AUTH_REPAIR_HARD_FAILURE_TYPES = frozenset({"human_verification"})AUTH_REPAIR_SINGLE_ATTEMPT_FAILURE_TYPES = frozenset( { "add_phone", "human_verification", "email_verification", "login_state_lost", "account_selection", "no_valid_organizations", })AUTH_REPAIR_RELEASE_AFTER_RETRY_TYPES = frozenset({"email_verification"})AUTH_REPAIR_RELEASE_TEAM_BLOCKER_TYPES = frozenset( { "login_state_lost", "account_selection", "no_valid_organizations", "missing_auth_file", "auth_error_discard", })
def _chatgpt_session_ready(chatgpt_api) -> bool:51 unmodified lines """本地 acc 是否有可用 auth_file(上游 `.upstream/manager.py:153`)。""" acc = acc or {} auth_file = (acc.get("auth_file") or "").strip() return bool(auth_file) and Path(auth_file).exists() return bool(auth_file) and _resolve_auth_file_path(auth_file).exists()
def get_mail_domain() -> str: """Return the configured mail domain used by registration/auth repair flows.""" from autoteam.runtime_config import get_register_domain
return get_register_domain()
def get_mail_provider_name() -> str: """Return the configured mail provider name used by registration/auth repair flows.""" return (os.environ.get("MAIL_PROVIDER") or "cf_temp_email").strip().lower()
def _mail_provider_name_for_client(mail_client) -> str: provider_name = str(getattr(mail_client, "provider_name", "") or "").strip().lower() if not provider_name: try: current = getattr(mail_client, "current_provider_name", None) if callable(current): provider_name = str(current() or "").strip().lower() except Exception: provider_name = "" if provider_name in {"maillab", "addy_io", "simplelogin"}: return provider_name if provider_name in {"cf_temp_email", "cloudflare_temp_email", "cloudmail"}: return "cf_temp_email" return get_mail_provider_name()
def _auth_search_dirs() -> tuple[Path, ...]: """Candidate auth directories for host and container path compatibility.""" candidates: list[Path] = [] try: from autoteam.auth_storage import AUTH_DIR
candidates.append(AUTH_DIR) except Exception: pass
project_root = Path(__file__).resolve().parents[2] candidates.extend((project_root / "data" / "auths", project_root / "auths"))
seen: set[str] = set() unique: list[Path] = [] for path in candidates: key = str(path) if key not in seen: seen.add(key) unique.append(path) return tuple(unique)
def _resolve_auth_file_path(value: str | None) -> Path: """Resolve auth paths saved as host paths, `/app/...`, `data/auths/...`, or bare names.""" text = (value or "").strip() if not text: return Path("")
direct = Path(text) if direct.exists(): return direct
project_root = Path(__file__).resolve().parents[2] candidates: list[Path] = [] normalized = text.replace("\\", "/") if normalized.startswith("/app/"): candidates.append(project_root / normalized.removeprefix("/app/")) elif normalized.startswith("data/") or normalized.startswith("auths/"): candidates.append(project_root / normalized)
name = Path(normalized).name if name: candidates.extend(auth_dir / name for auth_dir in _auth_search_dirs())
for candidate in candidates: if candidate.exists(): return candidate return direct
def _has_account_mail_binding(acc: dict | None) -> bool:16 unmodified lines return not _has_account_mail_binding(acc)
def _is_auth_repair_pending_status(status: str | None) -> bool: """Accept current persisted auth-invalid alias and legacy target auth_pending literal.""" return status in {STATUS_AUTH_PENDING, "auth_pending"}
def _can_attempt_auth_repair(acc: dict | None, mail_domain_suffix: str = "") -> bool: acc = acc or {} if ( bool(acc.get("mail_provider")) or acc.get("mail_account_id") is not None or acc.get("cloudmail_account_id") is not None ): return True email = _normalized_email(acc.get("email")) return bool(mail_domain_suffix and mail_domain_suffix in email)
def _sync_ready_credential_to_targets(email: str, auth_file: str | None, *, stage_label: str) -> dict: if not auth_file: logger.warning("%s 新凭证已就绪但缺少 auth_file,跳过即时同步: %s", stage_label, email)53 unmodified lines logger.warning("[IPv6Pool] release failed for %s: %s", email, exc)
def _discard_auth_repair_failed_account_record( email: str, reason: str, *, status: str = STATUS_STANDBY, now: float | None = None,) -> None: """Mark a released auth-repair failure as non-reusable while keeping local evidence.""" update_account( email, status=status, disabled=True, reuse_disabled=True, retired_at=time.time() if now is None else now, retired_reason=reason, ) _release_account_ipv6_proxy(email)
def _attach_account_proxy_to_bundle(email: str | None, bundle: dict | None, proxy_url: str | None = None) -> None: if not isinstance(bundle, dict): return239 unmodified lines "human_verification": "人机验证", "email_verification": "邮箱验证码页卡住", "workspace_selection": "workspace 选择未完成", "account_selection": "账号选择页未完成", "login_state_lost": "登录态丢失", "missing_auth_file": "缺少本地 Codex 凭证", "auth_error_discard": "认证失效后一次性丢弃", "unsupported_region": "出口地区不被 OAuth 接受", "oauth_timeout": "OAuth 授权页超时", "site_unavailable": "站点不可用/代理异常", "token_exchange_failed": "token 交换失败", "non_team_plan": "未进入 Team workspace",4 unmodified lines return mapping.get(error_type or "", error_type or "未知错误")
def _oauth_retry_delay_seconds(error_type: str | None) -> int: """Short same-round retry delays for transient OAuth organization/region pages.""" mapping = { "unsupported_region": 20, "account_selection": 6, "no_valid_organizations": 10, "oauth_timeout": 8, } return mapping.get(str(error_type or "").strip(), 0)
def _auth_repair_state_suffix(state: dict | None) -> str: """根据 auth_retry_after / auth_retry_paused 字段拼后缀(上游 `.upstream/manager.py:285`).""" state = state or {}100 unmodified lines error_detail = error_detail or _auth_repair_error_label(error_type) retry_delays = _auth_repair_retry_delays() release_team_seat = False missing_auth_file = not _has_auth_file(acc) team_blocking_status = acc.get("status") in (STATUS_STANDBY, STATUS_AUTH_INVALID) protected_local_credential = _is_protected_local_credential_seat(acc) try: from autoteam.config import ROTATE_SKIP_REUSE as discard_failed_repair except Exception: discard_failed_repair = True
if error_type == "add_phone" and _auth_repair_retry_add_phone_enabled(): prev_count = int(acc.get("auth_retry_count") or 0) if acc.get("auth_last_error") == "add_phone" else 031 unmodified lines "auth_retry_paused": True, } release_team_seat = True elif error_type in AUTH_REPAIR_RELEASE_TEAM_BLOCKER_TYPES and ( missing_auth_file or team_blocking_status or discard_failed_repair ): prev_count = int(acc.get("auth_retry_count") or 0) state = { "auth_retry_count": prev_count + 1, "auth_last_error": error_type, "auth_last_error_detail": error_detail, "auth_last_failed_at": now, "auth_retry_after": None, "auth_retry_paused": True, } release_team_seat = True else: prev_count = int(acc.get("auth_retry_count") or 0) next_count = min(prev_count + 1, len(retry_delays))7 unmodified lines "auth_retry_after": retry_after, "auth_retry_paused": False, } if error_type in AUTH_REPAIR_RELEASE_AFTER_RETRY_TYPES and next_count >= len(retry_delays): state["auth_retry_after"] = None state["auth_retry_paused"] = True release_team_seat = True
if release_team_seat and protected_local_credential: logger.warning("[认证修复] 保留受保护的本地凭证席位: %s", email) release_team_seat = False
update_account(email, **state)
13 unmodified lines # 走 default_machine.transition 时映射到 AccountState.AUTH_PENDING. final_status = STATUS_STANDBY if seat_released or not is_team_member else STATUS_AUTH_INVALID update_account(email, status=final_status, _reason=f"auth_repair:{error_type}") if discard_failed_repair and seat_released and not protected_local_credential: _discard_auth_repair_failed_account_record( email, f"auth_repair_failed:{error_type}", status=STATUS_STANDBY, now=now, )
return { **state,1 unmodified line "seat_released": seat_released, "release_attempted": release_attempted, "remove_status": remove_status, "protected_local_credential": protected_local_credential, }
def _login_codex_with_result( email: str, password: str, *, mail_client=None, max_attempts: int = 3, signup_profile: SignupProfile | None = None, pre_signed_in_cookies: list | None = None, playwright_proxy_url: str | None = None,) -> dict: """Run Codex OAuth with the explicit result wrapper used by auth repair.
This helper is intentionally isolated from `cmd_check` seat-release policy. It normalizes old bundle/None callers, current `return_result=True` callers, and rejected non-Team bundles into one retryable result shape. """ max_attempts = max(1, int(max_attempts))
def _reject_non_team(bundle: dict | None) -> dict | None: if not isinstance(bundle, dict) or not bundle: return None plan_type = str(bundle.get("plan_type") or "").lower() if plan_type == "team": return None return { "ok": False, "bundle": None, "error_type": "non_team_plan", "error_detail": f"登录后 plan={plan_type or 'unknown'},未进入 Team workspace", "retryable": True, }
def _result_from_legacy_bundle(bundle) -> dict: non_team = _reject_non_team(bundle if isinstance(bundle, dict) else None) if non_team: return non_team return { "ok": bool(bundle), "bundle": bundle if bundle else None, "error_type": None if bundle else "login_failed", "error_detail": None if bundle else "登录失败", "retryable": False if bundle else True, }
def _call_login(use_cookies: list | None) -> dict: kwargs = {"mail_client": mail_client, "return_result": True} if signup_profile is not None: kwargs["signup_profile"] = signup_profile if use_cookies is not None: kwargs["pre_signed_in_cookies"] = use_cookies if playwright_proxy_url is not None: kwargs["playwright_proxy_url"] = playwright_proxy_url
try: result = login_codex_via_browser(email, password, **kwargs) except TypeError: # Keep test doubles and older call signatures usable while current # production code accepts the extended kwargs above. result = login_codex_via_browser( email, password, mail_client=mail_client, return_result=True, ) except Exception as exc: return { "ok": False, "bundle": None, "error_type": "exception", "error_detail": str(exc), "retryable": True, }
if isinstance(result, dict) and "ok" in result: non_team = _reject_non_team(result.get("bundle")) if result.get("ok") and non_team: return non_team return result return _result_from_legacy_bundle(result)
last_result = None for attempt in range(1, max_attempts + 1): # Captured ChatGPT/Auth cookies are a first-attempt shortcut. If they # fail, later attempts fall back to the full login/OAuth path. use_cookies = pre_signed_in_cookies if attempt == 1 else None result = _call_login(use_cookies) result["attempts"] = attempt if result.get("ok"): return result
last_result = result error_type = result.get("error_type") retryable = bool(result.get("retryable")) if attempt >= max_attempts or not retryable or error_type in AUTH_REPAIR_SINGLE_ATTEMPT_FAILURE_TYPES: return result
logger.warning( "[Codex] %s 登录未完成(%s),准备在本轮重试第 %d/%d 次", email, _auth_repair_error_label(error_type), attempt + 1, max_attempts, ) retry_delay = _oauth_retry_delay_seconds(error_type) if retry_delay > 0: logger.info( "[Codex] %s 命中 %s,等待 %d 秒后重试以规避瞬时组织/出口抖动", email, _auth_repair_error_label(error_type), retry_delay, ) time.sleep(retry_delay)
return last_result or { "ok": False, "bundle": None, "error_type": "login_failed", "error_detail": "登录失败", "retryable": True, "attempts": max_attempts, }
38 unmodified lines 严格只接 -team-*.json:personal/plus/free 席位 auth 不能用于 Team 子号, 用错 plan 的 bundle 会被 OAuth 拒收(参考 codex-oauth personal 模式回退)。 """ try: from autoteam.auth_storage import AUTH_DIR except Exception: return None if not AUTH_DIR.exists(): return None candidates = sorted(AUTH_DIR.glob(f"codex-{email}-team-*.json")) candidates: list[Path] = [] for auth_dir in _auth_search_dirs(): if auth_dir.exists(): candidates.extend(sorted(auth_dir.glob(f"codex-{email}-team-*.json"))) return str(candidates[0]) if candidates else None
455 unmodified lines email = acc["email"].lower() in_team = email in team_emails
if in_team and acc["status"] in (STATUS_STANDBY, STATUS_PENDING): if in_team and acc["status"] in (STATUS_STANDBY, STATUS_PENDING, "auth_pending"): # Round 12 wire-up M1 — go through state machine (default_machine.transition). ws_id = account_id or None protect_team_seat = _has_auth_file(acc) _transition_status( acc["email"], STATUS_ACTIVE, workspace_account_id=ws_id, protect_team_seat=protect_team_seat, remote_seen_at=now_ts, _reason="sync_account_states:in_team", ) # 内存里也同步,后续 need_probe / domain_suffix 分支基于刷新后的状态判断 acc["status"] = STATUS_ACTIVE acc["remote_seen_at"] = now_ts if protect_team_seat: acc["protect_team_seat"] = True if account_id: acc["workspace_account_id"] = account_id changed = True136 unmodified lines # 判断是否在 Team 中 in_team = email in team_emails status = STATUS_ACTIVE if in_team else STATUS_STANDBY accounts.append( { "email": email, "password": "", "cloudmail_account_id": None, "status": status, "auth_file": str(auth_file), "quota_exhausted_at": None, "quota_resets_at": None, "created_at": time.time(), "last_active_at": None, } ) recovered = { "email": email, "password": "", "cloudmail_account_id": None, "status": status, "auth_file": str(auth_file), "quota_exhausted_at": None, "quota_resets_at": None, "created_at": time.time(), "last_active_at": None, } if in_team: recovered["protect_team_seat"] = True if account_id: recovered["workspace_account_id"] = account_id accounts.append(recovered) local_email_set.add(email) changed = True logger.info("[同步] 从 auths 目录恢复账号: %s(%s)", email, status)188 unmodified linesSTANDBY_PROBE_DEDUP_SEC = 24 * 3600 # 24h 内已探测过的 standby 跳过
def cmd_check(include_standby: bool = False):def cmd_check( include_standby: bool = False, *, force_auth_repair: bool = False, preserve_low_active: bool = False, preserved_low_accounts=None,): """检查 active 账号的额度,无认证文件或 auth_error 的自动重新登录 Codex。
参数: include_standby: True 时额外探测 standby 池每个账号的 quota(限速 + 24h 去重), 401/403 的标记为 STATUS_AUTH_INVALID。默认 False 保持向后兼容。 """ from autoteam.config import AUTO_CHECK_THRESHOLD, CLOUDMAIL_DOMAIN from autoteam.config import AUTO_CHECK_THRESHOLD
# API 运行时配置优先(前端可修改) try:128 unmodified lines
accounts = load_accounts()
all_active = [a for a in accounts if a["status"] == STATUS_ACTIVE and not _is_main_account_email(a.get("email"))] all_active = [ a for a in accounts if a["status"] == STATUS_ACTIVE and not _is_main_account_email(a.get("email")) and not is_account_disabled(a) ] auth_pending_accounts = [ a for a in accounts if _is_auth_repair_pending_status(a.get("status")) and not _is_main_account_email(a.get("email")) and not is_account_disabled(a) ]
# 区分:有认证文���的 vs 无认证文件的 active_with_auth = [] no_auth_list = [] skipped_repairs = [] mail_domain = get_mail_domain() mail_domain_suffix = mail_domain.lstrip("@") if mail_domain else "" for a in all_active: if a.get("auth_file") and Path(a["auth_file"]).exists(): if _has_auth_file(a): active_with_auth.append(a) else: # 只管我们域名的账号 if CLOUDMAIL_DOMAIN and CLOUDMAIL_DOMAIN.lstrip("@") in a["email"]: if _can_attempt_auth_repair(a, mail_domain_suffix): skip_reason = _auth_repair_skip_reason(a, force=force_auth_repair) if skip_reason: skipped_repairs.append((a["email"], skip_reason)) continue no_auth_list.append(a) for a in auth_pending_accounts: if _has_auth_file(a): active_with_auth.append(a) elif _can_attempt_auth_repair(a, mail_domain_suffix): skip_reason = _auth_repair_skip_reason(a, force=force_auth_repair) if skip_reason: skipped_repairs.append((a["email"], skip_reason)) continue no_auth_list.append(a)
if skipped_repairs: logger.info("[检查] 跳过 %d 个处于冷却/暂停中的认证修复账号:", len(skipped_repairs)) for email, reason in skipped_repairs: logger.info("[检查] %s(%s)", email, reason)
if not active_with_auth and not no_auth_list: logger.info("[检查] 没有可检查的 active 账号") logger.info("[检查] 没有可检查或可修复的账号") return []
# 检查有认证文件的账号额度4 unmodified lines logger.info("[检查] 检查 %d 个 active 账号的额度...", len(active_with_auth)) for acc in active_with_auth: email = acc["email"] was_auth_pending = _is_auth_repair_pending_status(acc.get("status")) status_str, info = _check_and_refresh(acc)
if status_str == "ok":8 unmodified lines update_account(email, last_quota=info) # 低于阈值视为用完 if p_remain < threshold: if preserve_low_active and not was_auth_pending: if preserved_low_accounts is not None: preserved_low_accounts.append( { "email": email, "remaining": p_remain, "quota": info, } ) logger.warning( "[%s] 5h剩余 %d%% < %d%%,先移后补模式暂不标记 exhausted (重置 %s)", email, p_remain, threshold, p_time, ) continue resets_at = p_reset or (time.time() + 18000) logger.warning( "[%s] 5h剩余 %d%% < %d%%,标记为 exhausted (重置 %s)", email, p_remain, threshold, p_time6 unmodified lines ) exhausted_list.append(acc) else: _auth_repair_reset(email) if was_auth_pending: update_account(email, status=STATUS_ACTIVE, last_active_at=time.time()) logger.info( "[%s] 认证已恢复 - 5h剩余: %d%% (重置 %s) | 周剩余: %d%% (重置 %s)", email, p_remain, p_time, w_remain, w_time, ) continue logger.info( "[%s] 额度可用 - 5h剩余: %d%% (重置 %s) | 周剩余: %d%% (重置 %s)", email,3 unmodified lines w_time, ) else: _auth_repair_reset(email) logger.info("[%s] 额度可用", email) elif status_str == "exhausted": quota_info = quota_result_quota_info(info) or {}56 unmodified lines else: logger.info("[%s] token 失效但 5h 重置时间已过,需重新登录验证", email) logger.warning("[%s] 认证失败,需要重新登录 Codex", email) skip_reason = _auth_repair_skip_reason(acc, force=force_auth_repair) if skip_reason: skipped_repairs.append((email, skip_reason)) else: auth_error_list.append(acc) auth_error_list.append(acc) elif status_str == "no_auth": skip_reason = _auth_repair_skip_reason(acc, force=force_auth_repair) if skip_reason: skipped_repairs.append((email, skip_reason)) else: auth_error_list.append(acc) elif status_str == "network_error": # 网络抖动/5xx/429:不算"额度用完",也不算"token 失效"。本轮跳过,不动 status, # 不进 exhausted_list,也不进 auth_error_list(避免触发昂贵的重登流程)。 logger.warning("[%s] 额度查询遇到临时网络错误,本轮跳过,等待下一轮重试", email) historical_low = _historical_low_quota_info(acc, threshold) if historical_low: quota_info = quota_result_quota_info(historical_low) or acc.get("last_quota") remaining = int(historical_low.get("remaining", 0) or 0) resets_at = quota_result_resets_at(historical_low) or int(time.time() + 18000) reset_time = time.strftime("%m-%d %H:%M", time.localtime(resets_at)) if resets_at else "?" if preserve_low_active and not was_auth_pending: if preserved_low_accounts is not None: preserved_low_accounts.append( { "email": email, "remaining": remaining, "quota": quota_info, } ) logger.warning( "[%s] 额度接口暂时不可达,但历史 5h 剩余 %d%% < %d%%,先移后补模式纳入轮换候选 (重置 %s)", email, remaining, threshold, reset_time, ) continue logger.warning( "[%s] 额度接口暂时不可达,但历史 5h 剩余 %d%% < %d%%,标记为 exhausted (重置 %s)", email, remaining, threshold, reset_time, ) update_account( email, status=STATUS_EXHAUSTED, last_quota=quota_info, quota_exhausted_at=time.time(), quota_resets_at=resets_at, ) exhausted_list.append(acc) continue logger.warning("[%s] 额度接口暂时不可达,保留当前凭证和席位状态,等待下一轮复查", email)
# 无认证文件的 active 账号也需要重新登录 # 无认证文件的 Team 内账号也需要重新登录 if no_auth_list: logger.info("[检查] 发现 %d 个 active 账号无认证文件,需要登录 Codex:", len(no_auth_list)) logger.info("[检查] 发现 %d 个 Team 内账号无认证文件,需要登录 Codex:", len(no_auth_list)) for a in no_auth_list: logger.info("[检查] %s", a["email"]) auth_error_list.extend(no_auth_list)27 unmodified lines auth_error_list = survivable_auth_errors
if auth_error_list: logger.info("[检查] 重新登录 %d 个 token 失效的账号...", len(auth_error_list)) mail_client = CloudMailClient() mail_client.login() logger.info("[检查] 重新登录 %d 个认证失效/待修复的账号...", len(auth_error_list)) mail_clients = {} for acc in auth_error_list: email = acc["email"] password = acc.get("password", "") logger.info("[%s] 重新 Codex 登录...", email) provider = (acc.get("mail_provider") or get_mail_provider_name()).strip().lower() mail_client = mail_clients.get(provider) if mail_client is None: mail_client = _get_account_mail_client(acc) mail_clients[provider] = mail_client auth_proxy_url, playwright_proxy_url = _ensure_account_ipv6_proxy(email) bundle = _login_codex_via_browser_with_proxy( email, password, mail_client=mail_client, playwright_proxy_url=playwright_proxy_url, ) if bundle: login_kwargs = {"mail_client": mail_client} if playwright_proxy_url: login_kwargs["playwright_proxy_url"] = playwright_proxy_url login_result = _login_codex_with_result(email, password, **login_kwargs) bundle = login_result.get("bundle") if login_result.get("ok") and bundle: _attach_account_proxy_to_bundle(email, bundle, auth_proxy_url) auth_file = save_auth_file(bundle) update_account(email, auth_file=auth_file) _auth_repair_reset(email) logger.info("[%s] token 已更新", email) # 重新检查额度 status_str, info = _check_and_refresh(find_account(load_accounts(), email))23 unmodified lines ) exhausted_list.append(acc) else: _auth_repair_reset(email) update_account(email, status=STATUS_ACTIVE, last_active_at=time.time()) logger.info("[%s] 额度可用 (%d%%)", email, p_remain) elif status_str == "ok": _auth_repair_reset(email) update_account(email, status=STATUS_ACTIVE, last_active_at=time.time()) logger.info("[%s] 额度可用", email) elif status_str == "auth_error": logger.warning("[%s] 重新登录后仍无法查询额度(可能未选中 Team workspace),标记为 standby", email) update_account(email, status=STATUS_STANDBY) result = _record_auth_repair_failure( email, login_result.get("error_type") or "non_team_plan", login_result.get("error_detail") or "重新登录后仍无法查询额度", ) extra = _auth_repair_result_suffix(result) logger.warning( "[%s] 重新登录后仍无法查询额度(可能未选中 Team workspace),标记为 %s%s", email, result.get("status"), extra, ) elif status_str == "network_error": _auth_repair_reset(email) update_account(email, status=STATUS_ACTIVE, last_active_at=time.time()) logger.warning("[%s] 重新登录成功,但额度接口暂时不可达;保留 active 并等待下一轮复查", email) else: logger.error("[%s] Codex 登录失败,标记为 standby", email) update_account(email, status=STATUS_STANDBY) result = _record_auth_repair_failure( email, login_result.get("error_type"), login_result.get("error_detail"), ) extra = _auth_repair_result_suffix(result) logger.error( "[%s] Codex 登录失败,标记为 %s(%s%s)", email, result.get("status"), _auth_repair_error_label(result.get("auth_last_error")), extra, )
# 已 exhausted 但 5h 重置时间已过 → 复测,真的回血则 promote 回 active,避免轮转 # 多走一遍"kick → standby → re-invite"。token 仍在 Team 里时这个直接 promote 路径978 unmodified lines return client
def _get_account_mail_client(acc: dict | None): """Compatibility wrapper for auth-repair paths that route mail per account.""" return _get_mail_client_for_account(acc)
def _resolve_mail_client_or_default(mail_client, acc=None): """统一处理 mail_client=None 入参:按 acc 路由或走全局默认。
143 unmodified lines password = acc.get("password") or random_password() else: password = random_password() add_account(inv_email, password, workspace_account_id=get_chatgpt_account_id() or None) add_account( inv_email, password, workspace_account_id=get_chatgpt_account_id() or None, mail_provider=_mail_provider_name_for_client(mail_client), )
# 关闭 ChatGPT 浏览器再注册 chatgpt_api.stop()35 unmodified lines)_DIRECT_PASSWORD_SELECTORS = 'input[name="password"], input[type="password"]'_DIRECT_CODE_SELECTORS = 'input[name="code"], input[placeholder*="验证码"], input[placeholder*="code" i]'_DIRECT_MULTI_CODE_SELECTOR = 'input[maxlength="1"]'_DIRECT_CODE_RENDER_TIMEOUT = 25
def _safe_invite_screenshot(page, name):36 unmodified lines return exhausted_info
def _first_visible_editable_locator(page, selectors, timeout=800):def _historical_low_quota_info(acc, threshold, now=None): """Return a low-quota decision from saved quota when live quota is unavailable.""" quota_info = acc.get("last_quota") if isinstance(acc, dict) else None if not isinstance(quota_info, dict): return None
current_ts = time.time() if now is None else now exhausted_info = _pending_historical_exhausted_info(quota_info, now=current_ts) if exhausted_info: result = dict(exhausted_info) result["remaining"] = 0 result["historical_low"] = True return result
try: locator = page.locator(selectors).first if not locator.is_visible(timeout=timeout): return None if locator.is_editable(timeout=timeout): return locator primary_pct = int(quota_info.get("primary_pct", 0) or 0) threshold_int = int(threshold) except Exception: return None
remaining = max(0, 100 - primary_pct) if remaining >= threshold_int: return None
try: primary_resets_at = int(quota_info.get("primary_resets_at", 0) or 0) except Exception: primary_resets_at = 0 if primary_resets_at and current_ts >= primary_resets_at: return None
return { "window": "primary", "resets_at": primary_resets_at or int(current_ts + 18000), "quota_info": quota_info, "remaining": remaining, "historical_low": True, }
def _first_visible_editable_locator(page, selectors, timeout=800): candidates = selectors if isinstance(selectors, (list, tuple)) else [selectors] for selector in candidates: try: locator = page.locator(selector).first if not locator.is_visible(timeout=timeout): continue if locator.is_editable(timeout=timeout): return locator except Exception: continue return None
def _visible_single_char_code_inputs(page, timeout=300): try: visible_inputs = [] for locator in page.locator(_DIRECT_MULTI_CODE_SELECTOR).all(): try: if locator.is_visible(timeout=timeout) and locator.is_editable(timeout=timeout): visible_inputs.append(locator) except Exception: continue if len(visible_inputs) >= 4: return visible_inputs except Exception: pass return []
def _wait_for_direct_code_target(page, timeout=_DIRECT_CODE_RENDER_TIMEOUT): deadline = time.time() + max(0.0, float(timeout))
while time.time() < deadline: split_inputs = _visible_single_char_code_inputs(page, timeout=300) if split_inputs: return {"mode": "split", "target": split_inputs}
code_input = _first_visible_editable_locator(page, _DIRECT_CODE_SELECTORS, timeout=300) if code_input: return {"mode": "single", "target": code_input}
step = _detect_direct_register_step(page) if step != "code": return {"mode": "advanced", "step": step} time.sleep(0.5)
step = _detect_direct_register_step(page) if step != "code": return {"mode": "advanced", "step": step} return {"mode": "timeout", "step": "code"}
def _submit_direct_verification_code(page, code_target, verification_code): mode = (code_target or {}).get("mode") target = (code_target or {}).get("target") submit_field = None current_step = _detect_direct_register_step(page)
if mode == "split" and isinstance(target, list): for index, char in enumerate(verification_code): if index >= len(target): break target[index].fill(char) time.sleep(0.1) if target: submit_field = target[0] elif mode == "single" and target: target.fill(verification_code) submit_field = target else: return _detect_direct_register_step(page)
time.sleep(0.5) if submit_field is not None: _click_primary_auth_button(page, submit_field, ["Continue", "继续", "Verify"]) return _wait_for_direct_step_change(page, current_step, timeout=20)
def _collect_date_spinbutton_meta(page): try: return page.evaluate(115 unmodified lines url = (page.url or "").lower() if _is_google_redirect(page): return "google" if "/api/auth/error" in url or url.endswith("/auth/error"): return "error"
if "email-verification" in url: return "code"39 unmodified lines deadline = time.time() + timeout while time.time() < deadline: step = _detect_direct_register_step(page) if step == "error": return step if step in allowed_steps: return step time.sleep(0.5)291 unmodified lines logger.warning("[直接注册] 邮箱步骤仍停留在 Google 登录页") cleanup_direct_register() return False, None if current_step == "error": logger.warning("[直接注册] 邮箱步骤进入认证错误页 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register() return False, None if current_step == "unknown": logger.warning("[直接注册] 邮箱步骤进入未知状态 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register() return False, None if current_step == "email": logger.warning("[直接注册] 邮箱步骤未推进 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register()8 unmodified lines # 等待页面跳转完成(可能跳到 create-account/password) password_step = _wait_for_direct_register_step( page, {"password", "code", "profile", "completed", "google", "email"}, {"password", "code", "profile", "completed", "google", "email", "error"}, timeout=15, ) logger.info("[直接注册] 密码页检测状态: %s | URL: %s", password_step, page.url) _safe_invite_screenshot(page, "direct_03b_before_password.png") if password_step == "error": logger.warning("[直接注册] 密码步骤进入认证错误页 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register() return False, None if password_step == "unknown": logger.warning("[直接注册] 无法识别密码/验证码步骤 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register() return False, None
try: for attempt in range(2):42 unmodified lines logger.warning("[直接注册] 密码步骤仍停留在 Google 登录页") cleanup_direct_register() return False, None if current_step == "error": logger.warning("[直接注册] 密码步骤进入认证错误页 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register() return False, None if current_step == "unknown": logger.warning("[直接注册] 密码步骤进入未知状态 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register() return False, None if current_step == "email": logger.warning("[直接注册] 提交密码前流程回退到邮箱页 | URL: %s | body=%s", page.url, _page_excerpt(page)) cleanup_direct_register()5 unmodified lines cleanup_direct_register() raise
code_input = None try: code_input = page.locator(_DIRECT_CODE_SELECTORS).first if not code_input.is_visible(timeout=5000): code_input = None except Exception: code_input = None code_step = _detect_direct_register_step(page) code_target = None if code_step == "code": logger.info("[直接注册] 等待验证码输入框渲染...") code_target_result = _wait_for_direct_code_target(page, timeout=_DIRECT_CODE_RENDER_TIMEOUT) mode = code_target_result.get("mode") if mode in {"single", "split"}: code_target = code_target_result logger.info("[直接注册] 验证码输入框已就绪(mode=%s)", mode) elif mode == "advanced": logger.info( "[直接注册] 验证码页等待期间流程已推进到 %s | URL: %s", code_target_result.get("step"), page.url, ) else: logger.warning( "[直接注册] 已停留在 email-verification 但 %ss 内未就绪验证码输入框 | URL: %s", _DIRECT_CODE_RENDER_TIMEOUT, page.url, )
if code_input: if code_target: logger.info("[直接注册] 等待验证码...") verification_code = None start_t = time.time()11 unmodified lines
if verification_code: logger.info("[直接注册] 输入验证码: %s", verification_code) code_input.fill(verification_code) time.sleep(0.5) _click_primary_auth_button(page, code_input, ["Continue", "继续"]) time.sleep(8) next_step = _submit_direct_verification_code(page, code_target, verification_code) logger.info("[直接注册] 验证码提交后状态: %s | URL: %s", next_step, page.url) else: logger.error("[直接注册] 未收到验证码") cleanup_direct_register()513 unmodified lines playwright_proxy_url = signup.get("playwright_proxy_url") or "" winner_mail_client = signup.get("mail_client") or mail_client
add_account(email, password, cloudmail_account_id=account_id, workspace_account_id=get_chatgpt_account_id() or None) add_account( email, password, cloudmail_account_id=account_id, workspace_account_id=get_chatgpt_account_id() or None, mail_provider=_mail_provider_name_for_client(winner_mail_client), mail_account_id=account_id, )
post_result = _run_post_register_oauth( email,2214 unmodified lines return result
def cmd_reset_quota_recovery(): """清空所有托管非主号账号的本地额度恢复记录。""" accounts = load_accounts() if not accounts: summary = { "total_accounts": 0, "updated_accounts": 0, "rearmed_exhausted_to_active": 0, "rearmed_exhausted_to_auth_pending": 0, } logger.info("[额度重置] 本地无账号记录") return summary
total_accounts = 0 updated_accounts = 0 rearmed_to_active = 0 rearmed_to_auth_pending = 0
for acc in accounts: email = acc.get("email", "") if _is_main_account_email(email): continue
total_accounts += 1 changed = False
for key in ("last_quota", "quota_resets_at", "quota_exhausted_at", "quota_window"): if acc.get(key) is not None: acc[key] = None changed = True
if acc.get("status") == STATUS_EXHAUSTED: desired_status = STATUS_ACTIVE if _has_auth_file(acc) else STATUS_AUTH_PENDING if acc.get("status") != desired_status: acc["status"] = desired_status changed = True if desired_status == STATUS_ACTIVE: rearmed_to_active += 1 else: rearmed_to_auth_pending += 1
if changed: updated_accounts += 1
if updated_accounts: save_accounts(accounts)
summary = { "total_accounts": total_accounts, "updated_accounts": updated_accounts, "rearmed_exhausted_to_active": rearmed_to_active, "rearmed_exhausted_to_auth_pending": rearmed_to_auth_pending, } logger.info( "[额度重置] 完成: 扫描 %d 个账号,更新 %d 个,恢复 exhausted -> active %d 个,exhausted -> auth_pending %d 个", total_accounts, updated_accounts, rearmed_to_active, rearmed_to_auth_pending, ) return summary
def _reconcile_master_degraded_subaccounts(*, dry_run: bool = False, chatgpt_api=None): """Round 8 — SPEC-2 v1.5 §3.5.3:reconcile retroactive 清理。
116 unmodified lines cleanup_p = sub.add_parser("cleanup", help="清理多余成员(只移除本地管理的)") cleanup_p.add_argument("max_seats", type=int, nargs="?", default=None, help="最大席位数")
sub.add_parser("reset-quota", help="清空本地额度恢复记录,并把 exhausted 账号恢复为可检查状态") sub.add_parser("sync", help="手动同步认证文件到 CPA") sub.add_parser("pull-cpa", help="从 CPA 反向同步认证文件到本地")
50 unmodified lines cmd_fill(args.target) elif args.command == "cleanup": cmd_cleanup(args.max_seats) elif args.command == "reset-quota": cmd_reset_quota_recovery() elif args.command == "sync": sync_to_cpa() elif args.command == "pull-cpa":2 unmodified lines345678924 unmodified lines343536373839404142434445464748495030 unmodified lines81828384858687129 unmodified lines21721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731812 unmodified lines3313323333343353363372 unmodified linesimport pytest
from autoteam import cpa_syncfrom autoteam import mail as mail_module
def test_list_cpa_files_raises_on_non_200(monkeypatch):24 unmodified lines cpa_sync.list_cpa_files()
def test_infer_mail_provider_from_email_uses_matching_domain(monkeypatch): monkeypatch.setenv("CLOUDMAIL_DOMAIN", "mail.example.com") monkeypatch.setenv("MAILLAB_DOMAIN", "lab.example.com") monkeypatch.setenv("ADDY_IO_DOMAIN", "alias.example.com")
assert mail_module.infer_mail_provider_from_email("user@mail.example.com") == "cf_temp_email" assert mail_module.infer_mail_provider_from_email("user@lab.example.com") == "maillab" assert mail_module.infer_mail_provider_from_email("user@alias.example.com") == "addy_io" assert mail_module.infer_mail_provider_from_email("user@unknown.example.com") == ""
def test_sync_to_cpa_skips_disabled_accounts_and_keeps_protected_remote(monkeypatch, tmp_path): enabled_auth = tmp_path / "codex-enabled@example.com-team-a.json" disabled_auth = tmp_path / "codex-disabled@example.com-team-b.json"30 unmodified lines
uploaded = [] deleted = [] monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", lambda *_args, **_kwargs: ("ok", {})) monkeypatch.setattr(cpa_sync, "upload_to_cpa", lambda path: uploaded.append(Path(path).name) or True) monkeypatch.setattr(cpa_sync, "delete_from_cpa", lambda name: deleted.append(name) or True)
129 unmodified lines assert result["delete_guard"]["skipped_protected"] == 1
def test_sync_to_cpa_skips_exhausted_active_credential_before_upload(monkeypatch, tmp_path): first_auth = tmp_path / "codex-first@example.com-team-a.json" second_auth = tmp_path / "codex-second@example.com-team-b.json" exhausted_auth = tmp_path / "codex-exhausted@example.com-team-c.json" first_auth.write_text('{"email":"first@example.com","access_token":"token-first"}', encoding="utf-8") second_auth.write_text('{"email":"second@example.com","access_token":"token-second"}', encoding="utf-8") exhausted_auth.write_text('{"email":"exhausted@example.com","access_token":"token-exhausted"}', encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ { "email": "first@example.com", "status": "active", "auth_file": str(first_auth), "disabled": False, "mail_provider": "cf_temp_email", "mail_account_id": "mail-1", }, { "email": "second@example.com", "status": "active", "auth_file": str(second_auth), "disabled": False, "mail_provider": "cf_temp_email", "mail_account_id": "mail-2", }, { "email": "exhausted@example.com", "status": "active", "auth_file": str(exhausted_auth), "disabled": False, "mail_provider": "cf_temp_email", "mail_account_id": "mail-3", }, ], ) monkeypatch.setattr("autoteam.accounts.save_accounts", lambda _accounts: None) monkeypatch.setattr(cpa_sync, "_cleanup_local_duplicates", lambda _accounts: (0, False)) monkeypatch.setattr( cpa_sync, "list_cpa_files", lambda: [ {"name": first_auth.name, "email": "first@example.com"}, {"name": second_auth.name, "email": "second@example.com"}, {"name": exhausted_auth.name, "email": "exhausted@example.com"}, ], )
def fake_quota(token, **_kwargs): if token == "token-exhausted": return "exhausted", {"primary_pct": 0} return "ok", {"primary_pct": 50}
uploaded = [] deleted = [] monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", fake_quota) monkeypatch.setattr(cpa_sync, "upload_to_cpa", lambda path: uploaded.append(Path(path).name) or True) monkeypatch.setattr(cpa_sync, "delete_from_cpa", lambda name: deleted.append(name) or True)
result = cpa_sync.sync_to_cpa()
assert uploaded == [first_auth.name, second_auth.name] assert deleted == [exhausted_auth.name] assert result["synced_active"] == 2 assert result["active_publish"]["delete_remote"] == 1 assert result["delete_guard"]["allow_remote_delete"] is True
def test_sync_to_cpa_keeps_remote_on_active_quota_network_error(monkeypatch, tmp_path): auth_file = tmp_path / "codex-active@example.com-team-a.json" auth_file.write_text('{"email":"active@example.com","access_token":"token-active"}', encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [{"email": "active@example.com", "status": "active", "auth_file": str(auth_file), "disabled": False}], ) monkeypatch.setattr("autoteam.accounts.save_accounts", lambda _accounts: None) monkeypatch.setattr(cpa_sync, "_cleanup_local_duplicates", lambda _accounts: (0, False)) monkeypatch.setattr(cpa_sync, "list_cpa_files", lambda: [{"name": auth_file.name, "email": "active@example.com"}])
uploaded = [] deleted = [] monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", lambda *_args, **_kwargs: ("network_error", {})) monkeypatch.setattr(cpa_sync, "upload_to_cpa", lambda path: uploaded.append(Path(path).name) or True) monkeypatch.setattr(cpa_sync, "delete_from_cpa", lambda name: deleted.append(name) or True)
result = cpa_sync.sync_to_cpa()
assert uploaded == [] assert deleted == [] assert result["synced_active"] == 0 assert result["active_publish"]["kept_remote"] == 1 assert result["delete_guard"]["allow_remote_delete"] is False
def test_sync_to_cpa_refreshes_proxy_url_before_upload(monkeypatch, tmp_path): auth_file = tmp_path / "codex-enabled@example.com-team-a.json" auth_file.write_text('{"email":"enabled@example.com","access_token":"token-enabled"}', encoding="utf-8")12 unmodified lines monkeypatch.setattr("autoteam.accounts.save_accounts", lambda _accounts: None) monkeypatch.setattr(cpa_sync, "_cleanup_local_duplicates", lambda _accounts: (0, False)) monkeypatch.setattr(cpa_sync, "list_cpa_files", lambda: []) monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", lambda *_args, **_kwargs: ("ok", {})) monkeypatch.setattr( "autoteam.ipv6_pool.ipv6_pool.ensure", lambda _email: "socks5://proxy.example:30000",73 unmodified lines7475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225146 unmodified lines37237337437537637737837938038138238338438573 unmodified lines self.page.active_element.typed.append(value)
class _FakeOtpInput: def __init__(self, *, visible=True, text=""): self.visible = visible self.text = text self.filled_values = [] self.clicked = False
def is_visible(self, timeout=0): return self.visible
def fill(self, value): self.filled_values.append(value)
def click(self, timeout=0, force=False): self.clicked = True
def type(self, value, delay=0): self.filled_values.append(value)
def inner_text(self, timeout=0): return self.text
class _FakeOtpCollection: def __init__(self, items=None, text=None): self._items = list(items or []) self._text = text
@property def first(self): if self._items: return self._items[0] return _FakeOtpInput(visible=False)
def all(self): return list(self._items)
def inner_text(self, timeout=0): if self._text is None: raise AssertionError("unexpected inner_text call") return self._text
class _FakeOtpPage: def __init__(self, *, url="https://auth.openai.com/email-verification", body="", slot_inputs=None, otp_input=None): self.url = url self._body = body self._slot_inputs = list(slot_inputs or []) self._otp_input = otp_input or _FakeOtpInput(visible=False) self.submit_button = _FakeOtpInput(visible=True) self.keyboard = type("_Keyboard", (), {"type": lambda _self, *_args, **_kwargs: None})()
def locator(self, selector): if selector == "body": return _FakeOtpCollection(text=self._body) if selector == codex_auth._OTP_SINGLE_INPUT_SELECTORS: return _FakeOtpCollection(items=self._slot_inputs) if selector == codex_auth._OTP_INPUT_SELECTORS: return _FakeOtpCollection(items=[self._otp_input]) if selector in { 'button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("继续")', 'button:has-text("Verify")', }: return _FakeOtpCollection(items=[self.submit_button]) return _FakeOtpCollection(items=[])
class _FakeChooseAccountPage: _GENERIC_SELECTORS = { "button", "a", '[role="button"]', '[role="option"]', '[aria-selected="true"]', '[aria-selected="false"]', "[data-state]", "li", "label", "div", }
def __init__(self, *, account_elements, continue_button=None): self.url = "https://auth.openai.com/choose-an-account" self._account_elements = list(account_elements) self._continue_button = continue_button or _FakeOtpInput(visible=False)
def locator(self, selector): if selector == "body": return _FakeOtpCollection(text="Choose an account Continue as user@example.com") if selector == 'button:has-text("Continue"), button:has-text("继续"), button:has-text("Allow")': return _FakeOtpCollection(items=[self._continue_button]) if selector in self._GENERIC_SELECTORS: return _FakeOtpCollection(items=self._account_elements) return _FakeOtpCollection(items=[])
def test_codex_otp_helper_fills_segmented_inputs(): slots = [_FakeOtpInput() for _ in range(6)] page = _FakeOtpPage(slot_inputs=slots)
assert codex_auth._fill_otp_code(page, "481556") is True
assert [slot.filled_values[-1] for slot in slots] == list("481556")
def test_codex_resolve_email_verification_marks_used_after_success(monkeypatch): slots = [_FakeOtpInput() for _ in range(6)] page = _FakeOtpPage(slot_inputs=slots) used_email_ids = set()
monkeypatch.setattr(codex_auth, "_poll_mail_verification_code", lambda *args, **kwargs: ("481556", 1888)) monkeypatch.setattr(codex_auth, "_wait_for_otp_submit_result", lambda *args, **kwargs: ("accepted", None)) monkeypatch.setattr(codex_auth.time, "sleep", lambda *_args, **_kwargs: None)
status = codex_auth._resolve_email_verification( page, mail_client=object(), email="user@example.com", after_email_id=1000, used_email_ids=used_email_ids, wait_log="[Codex] test wait emailId > %d", )
assert status == "accepted" assert used_email_ids == {1888} assert [slot.filled_values[-1] for slot in slots] == list("481556") assert page.submit_button.clicked is True
def test_codex_select_oauth_account_clicks_matching_email(monkeypatch): other = _FakeOtpInput(text="other@example.com") target = _FakeOtpInput(text="user@example.com") confirm = _FakeOtpInput(text="Continue") page = _FakeChooseAccountPage(account_elements=[other, target], continue_button=confirm)
monkeypatch.setattr(codex_auth.time, "sleep", lambda *_args, **_kwargs: None)
assert codex_auth._is_choose_account_page(page) is True assert codex_auth._select_oauth_account(page, "user@example.com") is True assert other.clicked is False assert target.clicked is True assert confirm.clicked is True
class _FakeOAuthAboutYouPage: def __init__(self, *, spinbuttons=True, expected_order=None): self.url = "https://auth.openai.com/about-you"146 unmodified lines assert captured["oauth"]["leave_workspace"] is True
def test_direct_register_step_recognizes_auth_error_page(monkeypatch): page = type("_Page", (), {"url": "https://chatgpt.com/api/auth/error"})()
monkeypatch.setattr(manager_mod, "_is_google_redirect", lambda _page: False)
assert manager_mod._detect_direct_register_step(page) == "error"
def test_create_account_direct_races_signup_workers_and_uses_winner(monkeypatch): calls = [] added = []237 unmodified lines238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321237 unmodified lines assert not missing, f"SessionCodexAuthFlow 缺少必需方法: {missing}"
def test_main_codex_login_flow_saves_without_remote_sync(monkeypatch): """MainCodexLoginFlow 只保存本地主号 auth,不调用远端同步。""" from autoteam import codex_auth
sync_calls = []
monkeypatch.setattr(codex_auth, "get_admin_email", lambda: "admin@example.com") monkeypatch.setattr(codex_auth, "get_admin_session_token", lambda: "fake-session-token-abc123") monkeypatch.setattr(codex_auth, "get_chatgpt_account_id", lambda: "ws-account-uuid-xyz") monkeypatch.setattr(codex_auth, "get_chatgpt_workspace_name", lambda: "Master Team") monkeypatch.setattr("autoteam.admin_state.get_admin_password", lambda: "admin-password") monkeypatch.setattr( codex_auth.SessionCodexAuthFlow, "complete", lambda self: { "email": "admin@example.com", "auth_file": "/tmp/codex-main-ws-account-uuid-xyz.json", "plan_type": "team", "bundle": _make_complete_bundle(), }, ) monkeypatch.setattr( "autoteam.sync_targets.sync_main_codex_to_configured_targets", lambda filepath: sync_calls.append(filepath), )
result = codex_auth.MainCodexLoginFlow().complete()
assert result == { "email": "admin@example.com", "auth_file": "/tmp/codex-main-ws-account-uuid-xyz.json", "plan_type": "team", } assert sync_calls == []
def test_main_codex_login_flow_passes_saved_admin_password(monkeypatch): """主号 Codex 登录在 OTP 入口不可用时可回退保存的管理员密码。""" from autoteam import codex_auth
captured = {}
def fake_init(self, **kwargs): captured.update(kwargs)
monkeypatch.setattr(codex_auth, "get_admin_email", lambda: "admin@example.com") monkeypatch.setattr(codex_auth, "get_admin_session_token", lambda: "fake-session-token-abc123") monkeypatch.setattr(codex_auth, "get_chatgpt_account_id", lambda: "ws-account-uuid-xyz") monkeypatch.setattr(codex_auth, "get_chatgpt_workspace_name", lambda: "Master Team") monkeypatch.setattr("autoteam.admin_state.get_admin_password", lambda: "admin-password") monkeypatch.setattr(codex_auth.SessionCodexAuthFlow, "__init__", fake_init)
codex_auth.MainCodexLoginFlow()
assert captured["password"] == "admin-password"
def test_session_codex_auth_flow_uses_password_when_otp_switch_unavailable(monkeypatch): from autoteam import codex_auth
flow = codex_auth.SessionCodexAuthFlow( email="admin@example.com", session_token="session-token", account_id="account-id", workspace_name="workspace", password="admin-password", ) steps = iter([("password_required", None), ("completed", None)]) calls = []
monkeypatch.setattr(flow, "_detect_step", lambda: next(steps)) monkeypatch.setattr(flow, "_switch_password_to_otp", lambda: False) monkeypatch.setattr(flow, "_auto_fill_password", lambda: calls.append("password") or True)
assert flow._advance(attempts=2) == {"step": "completed", "detail": None} assert calls == ["password"]
def test_inject_auth_cookies_guards_account_id(): """_inject_auth_cookies 必须用 `if self.account_id:` 守护,避免空字符串污染 _account cookie.
.trellis/spec/backend/account-disable-cpa-sync.mdAdded+290
.trellis/spec/backend/index.md+2-1
.trellis/tasks/05-19-autoteam1-full-parity-completion-audit/prd.mdAdded+178
.trellis/tasks/05-19-autoteam1-full-parity-completion-audit/research/autoteam1-full-parity-matrix.mdAdded+624
src/autoteam/accounts.py+38-1
src/autoteam/codex_auth.py+1132-146
src/autoteam/cpa_sync.py+31-1
src/autoteam/mail/__init__.py+34
src/autoteam/manager.py+767-70
tests/unit/test_cpa_sync.py+110
tests/unit/test_free_registration_hardening.py+154
tests/unit/test_round10_master_codex_session.py+78