Spaces:
Paused
Paused
Harden AutoTeam runtime and free registration
Browse filesFiles changed (48)
- .env.example+8
- .trellis/spec/backend/database-guidelines.mdAdded+51
- .trellis/spec/backend/directory-structure.mdAdded+54
- .trellis/spec/backend/error-handling.mdAdded+51
- .trellis/spec/backend/free-registration-hardening.mdAdded+88
- .trellis/spec/backend/index.mdAdded+40
- .trellis/spec/backend/logging-guidelines.mdAdded+51
- .trellis/spec/backend/quality-guidelines.mdAdded+51
- .trellis/spec/backend/runtime-docker-hardening.mdAdded+104
- .trellis/spec/guides/code-reuse-thinking-guide.mdAdded+105
- .trellis/spec/guides/cross-layer-thinking-guide.mdAdded+94
- .trellis/spec/guides/index.mdAdded+79
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/check.jsonlAdded+30
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/completion-audit-2026-05-15.mdAdded+53
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/free-registration-round2-completion-audit.mdAdded+37
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/implement.jsonlAdded+14
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/prd.mdAdded+62
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/research/docker-playwright-hardening.mdAdded+24
- .trellis/tasks/05-15-autoteam1-hardening-docker-apply/task.jsonAdded+26
- Dockerfile.fastAdded+29
- docker-compose.yml+15
- docker-entrypoint.sh+16-9
- docs/docker.md+51-1
- prompts/0515/autoteam1-absorption-audit.mdAdded+59
- prompts/0515/free-registration-round2-critical-audit.mdAdded+112
- prompts/0515/implementation-plan.mdAdded+113
- prompts/0515/prd.mdAdded+122
- prompts/0515/research-docker-playwright-hardening.mdAdded+52
- prompts/0515/spec.mdAdded+142
- pyproject.toml+1
- src/autoteam/api.py+137-9
- src/autoteam/chatgpt_api.py+255-56
- src/autoteam/chatgpt_transport.pyAdded+99
- src/autoteam/codex_auth.py+6-1
- src/autoteam/config.py+56-1
- src/autoteam/manager.py+31-31
- src/autoteam/playwright_lifecycle.pyAdded+38
- src/autoteam/playwright_probe.pyAdded+45
- src/autoteam/runtime_resources.pyAdded+182
- src/autoteam/signup_profile.py+67-7
- tests/integration/test_docker_guard.py+62
- tests/unit/test_api_playwright_cleanup.pyAdded+155
- tests/unit/test_chatgpt_transport.pyAdded+174
- tests/unit/test_free_registration_hardening.pyAdded+22
- tests/unit/test_round12_s3_cherry_pick.py+16-1
- tests/unit/test_round12_wireup.py+5-7
- tests/unit/test_runtime_resources.pyAdded+100
- uv.lock+126
31 unmodified lines32333435363731 unmodified lines# 示例:localhost,127.0.0.1PLAYWRIGHT_PROXY_BYPASS=# 轮询配置EMAIL_POLL_INTERVAL=3EMAIL_POLL_TIMEOUT=30031 unmodified lines323334353637383940414243444531 unmodified lines# 示例:localhost,127.0.0.1PLAYWRIGHT_PROXY_BYPASS=# ChatGPT Team API transport(默认对齐 autoteam-1,Team API 读取优先轻量 HTTP)# 可选值:playwright | curl_cffi | auto# - playwright:保持旧行为,所有 Team API 通过浏览器上下文 fetch# - curl_cffi / auto:优先尝试轻量 HTTP transport,异常或挑战页会回退 PlaywrightCHATGPT_API_TRANSPORT=autoCHATGPT_API_HTTP_TIMEOUT=60CHATGPT_API_IMPERSONATE=chrome136# 轮询配置EMAIL_POLL_INTERVAL=3EMAIL_POLL_TIMEOUT=300
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Database Guidelines
> Database patterns and conventions for this project.
---
## Overview
<!--Document your project's database conventions here.
Questions to answer:- What ORM/query library do you use?- How are migrations managed?- What are the naming conventions for tables/columns?- How do you handle transactions?-->
(To be filled by the team)
---
## Query Patterns
<!-- How should queries be written? Batch operations? -->
(To be filled by the team)
---
## Migrations
<!-- How to create and run migrations -->
(To be filled by the team)
---
## Naming Conventions
<!-- Table names, column names, index names -->
(To be filled by the team)
---
## Common Mistakes
<!-- Database-related mistakes your team has made -->
(To be filled by the team)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# Directory Structure
> How backend code is organized in this project.
---
## Overview
<!--Document your project's backend directory structure here.
Questions to answer:- How are modules/packages organized?- Where does business logic live?- Where are API endpoints defined?- How are utilities and helpers organized?-->
(To be filled by the team)
---
## Directory Layout
```<!-- Replace with your actual structure -->src/├── ...└── ...```
---
## Module Organization
<!-- How should new features/modules be organized? -->
(To be filled by the team)
---
## Naming Conventions
<!-- File and folder naming rules -->
(To be filled by the team)
---
## Examples
<!-- Link to well-organized modules as examples -->
(To be filled by the team)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Error Handling
> How errors are handled in this project.
---
## Overview
<!--Document your project's error handling conventions here.
Questions to answer:- What error types do you define?- How are errors propagated?- How are errors logged?- How are errors returned to clients?-->
(To be filled by the team)
---
## Error Types
<!-- Custom error classes/types -->
(To be filled by the team)
---
## Error Handling Patterns
<!-- Try-catch patterns, error propagation -->
(To be filled by the team)
---
## API Error Responses
<!-- Standard error response format -->
(To be filled by the team)
---
## Common Mistakes
<!-- Error handling mistakes your team has made -->
(To be filled by the team)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# Free Registration Hardening
## Scenario: Fill-Personal Safety Boundary
### 1. Scope / Trigger
- Trigger: any change to `POST /api/tasks/fill`, `cmd_fill(..., leave_workspace=True)`, `_cmd_fill_personal()`, `create_account_direct(..., leave_workspace=True)`, `_run_post_register_oauth(..., leave_workspace=True)`, or `SignupProfile`.- Goal: make the free-account registration flow safer and more diagnosable without changing the successful-path semantics.- Safety boundary: do not add bypasses for captcha, human verification, platform restrictions, rate limits, or anti-abuse systems. Hardening means consistency, early rejection, cleanup, and auditability.
### 2. Signatures
- `TaskParams.leave_workspace: bool = False`- `post_fill(params: TaskParams = TaskParams())`- `cmd_fill(target=5, leave_workspace=False)`- `_cmd_fill_personal(count)`- `create_new_account(chatgpt_api, mail_client=None, *, leave_workspace=False, out_outcome=None, acc=None, path_rotator=None)`- `create_account_direct(mail_client=None, *, leave_workspace=False, out_outcome=None, acc=None, path_rotator=None)`- `_run_post_register_oauth(email, password, mail_client, leave_workspace=False, out_outcome=None, chatgpt_session_token=None)`- `generate_signup_profile(*, today: date | None = None, rng: random.Random | random.SystemRandom | None = None) -> SignupProfile`
### 3. Contracts
- API command mapping must remain: - `leave_workspace=True` -> `"fill-personal"` - `leave_workspace=False` -> `"fill"`- The free path must remain: - register into Team - remove from Team with master authority - run Personal OAuth - accept only `plan_type == "free"` - persist `STATUS_PERSONAL`- API-level fill-personal preflight must use the same local Team-seat definition as `manager._count_local_team_seat_accounts()`.- Local Team-seat statuses are `STATUS_ACTIVE`, `STATUS_EXHAUSTED`, and `STATUS_AUTH_INVALID`; `STATUS_PERSONAL` is not a Team seat.- `SignupProfile` must be a single immutable snapshot passed through registration and OAuth. Its birthday and age must also be self-consistent.- `CHATGPT_API_TRANSPORT` defaults to `auto` for Team backend API reads, matching `D:\Desktop\autoteam-1\AutoTeam`; free registration and Personal OAuth still require a real browser context and must not rely on HTTP-only transport.
### 4. Validation & Error Matrix
| Condition | Required behavior || --- | --- || local Team seats >= `TEAM_SUB_ACCOUNT_HARD_CAP` before fill-personal | API returns 409 and does not start a background task || local Team seats include `STATUS_AUTH_INVALID` | Count them as occupied seats || generated birthday implies age outside allowed range | raise `ValueError` during profile generation || Personal OAuth gets `plan_type != "free"` or no bundle | retry up to the existing 5-attempt policy, then record plan drift and fail fast || `remove_from_team` fails before Personal OAuth | mark/keep safe local state, record `kick_failed`, and do not run Personal OAuth || `RegisterBlocked` phone/add-phone | terminal failure, record category, delete or quarantine according to existing manager logic |
### 5. Good/Base/Bad Cases
- Good: API rejects fill-personal when the local seat set is `{active, exhausted, auth_invalid, auth_invalid}`.- Base: a normal `leave_workspace=False` fill does not use the free-path preflight.- Bad: counting only `active/exhausted` at API level while manager counts `auth_invalid` as a seat, because that starts a task that should have been rejected before browser/mail work.
### 6. Tests Required
- Profile consistency: - `tests/unit/test_round12_s3_cherry_pick.py` - assert `profile.age == calculate_age(profile.birth_date, today)`- API preflight: - `tests/unit/test_free_registration_hardening.py` - assert `auth_invalid` contributes to Team-seat hard-cap rejection- Main free registration regression: - `tests/unit/test_round11_personal_oauth_retry.py` - `tests/unit/test_round11_session_token_injection.py` - `tests/unit/test_round12_s4_register_dual_path.py` - `tests/unit/test_manager_fill.py`
### 7. Wrong vs Correct
#### Wrong
```pythonin_team_local = sum( 1 for a in load_accounts() if a.get("status") in (STATUS_ACTIVE, STATUS_EXHAUSTED))```
This misses `STATUS_AUTH_INVALID`, which the manager treats as a Team-seat occupant.
#### Correct
```pythonin_team_local = _count_local_team_seat_accounts(load_accounts())```
Keep the API entrypoint and manager entrypoint aligned so unsafe fill-personal work is rejected before starting browser or mail-provider operations.12345678910111213141516171819202122232425262728293031323334353637383940# Backend Development Guidelines
> Best practices for backend development in this project.
---
## Overview
This directory contains guidelines for backend development. Fill in each file with your project's specific conventions.
---
## Guidelines Index
| Guide | Description | Status ||-------|-------------|--------|| [Directory Structure](./directory-structure.md) | Module organization and file layout | To fill || [Database Guidelines](./database-guidelines.md) | ORM patterns, queries, migrations | To fill || [Error Handling](./error-handling.md) | Error types, handling strategies | To fill || [Quality Guidelines](./quality-guidelines.md) | Code standards, forbidden patterns | To fill || [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, and transport safety | Active || [Free Registration Hardening](./free-registration-hardening.md) | Fill-personal safety boundaries, Team-seat preflight, and SignupProfile consistency | Active |
---
## How to Fill These Guidelines
For each guideline file:
1. Document your project's **actual conventions** (not ideals)2. Include **code examples** from your codebase3. List **forbidden patterns** and why4. Add **common mistakes** your team has made
The goal is to help AI assistants and new team members understand how YOUR project works.
---
**Language**: All documentation should be written in **English**.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Logging Guidelines
> How logging is done in this project.
---
## Overview
<!--Document your project's logging conventions here.
Questions to answer:- What logging library do you use?- What are the log levels and when to use each?- What should be logged?- What should NOT be logged (PII, secrets)?-->
(To be filled by the team)
---
## Log Levels
<!-- When to use each level: debug, info, warn, error -->
(To be filled by the team)
---
## Structured Logging
<!-- Log format, required fields -->
(To be filled by the team)
---
## What to Log
<!-- Important events to log -->
(To be filled by the team)
---
## What NOT to Log
<!-- Sensitive data, PII, secrets -->
(To be filled by the team)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Quality Guidelines
> Code quality standards for backend development.
---
## Overview
<!--Document your project's quality standards here.
Questions to answer:- What patterns are forbidden?- What linting rules do you enforce?- What are your testing requirements?- What code review standards apply?-->
(To be filled by the team)
---
## Forbidden Patterns
<!-- Patterns that should never be used and why -->
(To be filled by the team)
---
## Required Patterns
<!-- Patterns that must always be used -->
(To be filled by the team)
---
## Testing Requirements
<!-- What level of testing is expected -->
(To be filled by the team)
---
## Code Review Checklist
<!-- What reviewers should check -->
(To be filled by the team)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# Runtime and Docker Hardening
## Scenario: Docker-Bounded Playwright Runtime
### 1. Scope / Trigger
- Trigger: any change that touches Docker runtime settings, Playwright lifecycle management, runtime resource probes, background browser probes, or `CHATGPT_API_TRANSPORT`.- Goal: keep browser automation bounded and observable without changing the free-account registration main flow.- Applies to: - `docker-compose.yml` - `Dockerfile.fast` - `docker-entrypoint.sh` - `src/autoteam/runtime_resources.py` - `src/autoteam/playwright_lifecycle.py` - `src/autoteam/playwright_probe.py` - `src/autoteam/chatgpt_transport.py` - `src/autoteam/chatgpt_api.py` - `src/autoteam/api.py`
### 2. Signatures
- `collect_runtime_resource_snapshot() -> dict[str, Any]`- `log_runtime_resource_snapshot(logger: Any, *, label: str = "runtime") -> dict[str, Any]`- `close_playwright_objects(page=None, context=None, browser=None, playwright=None, *, logger=None, label="playwright") -> None`- `python -m autoteam.playwright_probe team-member-count`- `ChatGPTTeamAPI.start_with_session(session_token, account_id, workspace_name="", require_browser=False)`- `ChatGPTTeamAPI.stop() -> None`- `build_chatgpt_transport(session_token: str, account_id: str = "", oai_device_id: str = "")`
### 3. Contracts
- Docker Compose must keep: - `services.autoteam.init: true` - `services.autoteam.shm_size` at least `1gb` - `services.autoteam.mem_limit` and `memswap_limit` - `services.autoteam.pids_limit` - healthcheck using `curl -fsS http://127.0.0.1:8787/api/version` - build args `GIT_SHA` and `BUILD_TIME`- Runtime env keys: - `AUTOTEAM_MEMORY_WARN_RATIO`, default `0.85` - `AUTOTEAM_ZOMBIE_WARN_THRESHOLD`, default `20` in code; compose may use a stricter value - `CHATGPT_API_TRANSPORT`, default `auto` to match `D:\Desktop\autoteam-1\AutoTeam` - `CHATGPT_API_HTTP_TIMEOUT`, default `60` - `CHATGPT_API_IMPERSONATE`, default `chrome136`- `CHATGPT_API_TRANSPORT=curl_cffi` or `auto` is allowed only for backend API reads. It must not be used for free registration, Personal OAuth, captcha/challenge flows, or workspace UI selection; those call sites must force `require_browser=True` or launch their own Playwright context.- `/api/status` may include `runtime_resources`, but resource collection must never block or fail the status response.- Background Team member count probes must run in a killable subprocess and return unknown (`-1`) on timeout/failure.
### 4. Validation & Error Matrix
| Condition | Required behavior || --- | --- || `/proc` or cgroup files missing | Resource snapshot fields become `None`; no exception escapes || `ps` unavailable or times out | Browser process counts become zero; no exception escapes || cgroup memory ratio >= threshold | Log a warning and run best-effort `gc.collect()` || browser zombie count >= threshold | Log a warning that init/reaper should be enabled || Playwright page/context/browser/stop raises during cleanup | Log debug when logger exists; continue cleanup and do not re-raise || `_launch_browser()` partially initializes then fails | Call `stop()` and re-raise the original exception || probe subprocess timeout | Kill the process group/tree and treat count as unknown || `curl_cffi` missing or transport init fails | Return `None`; continue with Playwright || transport returns HTML/challenge/401 token missing | Fall back to Playwright API fetch || `ChatGPTTeamAPI.start()` succeeds via HTTP transport only | Cleanup and reuse checks must use `is_started()` / `_chatgpt_session_ready()`, not `browser` alone |
### 5. Good/Base/Bad Cases
- Good: `docker compose config` shows init, shm, memory, PID, healthcheck, and build args; `docker run --rm autoteam:fast-0515 status` passes self-check.- Base: local non-Docker startup still uses the same Python modules and defaults to `auto`, while browser-dependent flows force Playwright explicitly.- Bad: letting `auto` leak into OAuth/UI flows, swallowing Playwright init failures without cleanup, or running periodic Team count checks in the long-lived API process.- Bad: guarding `stop()` with `if api.browser` after `auto` transport is enabled; HTTP-only sessions would leak.
### 6. Tests Required
- Docker contract: `tests/integration/test_docker_guard.py`- Resource probe: `tests/unit/test_runtime_resources.py`- Playwright cleanup and subprocess probe behavior: `tests/unit/test_api_playwright_cleanup.py`- HTTP transport auto/fallback: `tests/unit/test_chatgpt_transport.py`- Status endpoint integration: `tests/unit/test_api_status.py`- Free registration regression: - `tests/unit/test_round11_personal_oauth_retry.py` - `tests/unit/test_round11_session_token_injection.py` - `tests/unit/test_round12_s4_register_dual_path.py` - `tests/unit/test_manager_fill.py`
### 7. Wrong vs Correct
#### Wrong
```pythondef start_with_session(self, session_token, account_id): self.http_transport = build_chatgpt_transport(...) # This silently changes all callers to HTTP-first behavior, including flows # that require a real browser context.```
#### Correct
```pythondef start_with_session(self, session_token, account_id, workspace_name="", require_browser=False): if not require_browser and self._start_transport_session(session_token): ... self._start_browser_session(session_token)```
Use `require_browser=True` for any path that depends on a real browser context. Keep the default environment value aligned with `autoteam-1` as `auto`, and keep `curl_cffi` isolated to backend API reads/writes plus browser fallback.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105# Code Reuse Thinking Guide
> **Purpose**: Stop and think before creating new code - does it already exist?
---
## The Problem
**Duplicated code is the #1 source of inconsistency bugs.**
When you copy-paste or rewrite existing logic:- Bug fixes don't propagate- Behavior diverges over time- Codebase becomes harder to understand
---
## Before Writing New Code
### Step 1: Search First
```bash# Search for similar function namesgrep -r "functionName" .
# Search for similar logicgrep -r "keyword" .```
### Step 2: Ask These Questions
| Question | If Yes... ||----------|-----------|| Does a similar function exist? | Use or extend it || Is this pattern used elsewhere? | Follow the existing pattern || Could this be a shared utility? | Create it in the right place || Am I copying code from another file? | **STOP** - extract to shared |
---
## Common Duplication Patterns
### Pattern 1: Copy-Paste Functions
**Bad**: Copying a validation function to another file
**Good**: Extract to shared utilities, import where needed
### Pattern 2: Similar Components
**Bad**: Creating a new component that's 80% similar to existing
**Good**: Extend existing component with props/variants
### Pattern 3: Repeated Constants
**Bad**: Defining the same constant in multiple files
**Good**: Single source of truth, import everywhere
---
## When to Abstract
**Abstract when**:- Same code appears 3+ times- Logic is complex enough to have bugs- Multiple people might need this
**Don't abstract when**:- Only used once- Trivial one-liner- Abstraction would be more complex than duplication
---
## After Batch Modifications
When you've made similar changes to multiple files:
1. **Review**: Did you catch all instances?2. **Search**: Run grep to find any missed3. **Consider**: Should this be abstracted?
---
## Gotcha: Asymmetric Mechanisms Producing Same Output
**Problem**: When two different mechanisms must produce the same file set (e.g., recursive directory copy for init vs. manual `files.set()` for update), structural changes (renaming, moving, adding subdirectories) only propagate through the automatic mechanism. The manual one silently drifts.
**Symptom**: Init works perfectly, but update creates files at wrong paths or misses files entirely.
**Prevention checklist**:- [ ] When migrating directory structures, search for ALL code paths that reference the old structure- [ ] If one path is auto-derived (glob/copy) and another is manually listed, the manual one needs updating- [ ] Add a regression test that compares outputs from both mechanisms
---
## Checklist Before Commit
- [ ] Searched for existing similar code- [ ] No copy-pasted logic that should be shared- [ ] Constants defined in one place- [ ] Similar patterns follow same structure12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Cross-Layer Thinking Guide
> **Purpose**: Think through data flow across layers before implementing.
---
## The Problem
**Most bugs happen at layer boundaries**, not within layers.
Common cross-layer bugs:- API returns format A, frontend expects format B- Database stores X, service transforms to Y, but loses data- Multiple layers implement the same logic differently
---
## Before Implementing Cross-Layer Features
### Step 1: Map the Data Flow
Draw out how data moves:
```Source → Transform → Store → Retrieve → Transform → Display```
For each arrow, ask:- What format is the data in?- What could go wrong?- Who is responsible for validation?
### Step 2: Identify Boundaries
| Boundary | Common Issues ||----------|---------------|| API ↔ Service | Type mismatches, missing fields || Service ↔ Database | Format conversions, null handling || Backend ↔ Frontend | Serialization, date formats || Component ↔ Component | Props shape changes |
### Step 3: Define Contracts
For each boundary:- What is the exact input format?- What is the exact output format?- What errors can occur?
---
## Common Cross-Layer Mistakes
### Mistake 1: Implicit Format Assumptions
**Bad**: Assuming date format without checking
**Good**: Explicit format conversion at boundaries
### Mistake 2: Scattered Validation
**Bad**: Validating the same thing in multiple layers
**Good**: Validate once at the entry point
### Mistake 3: Leaky Abstractions
**Bad**: Component knows about database schema
**Good**: Each layer only knows its neighbors
---
## Checklist for Cross-Layer Features
Before implementation:- [ ] Mapped the complete data flow- [ ] Identified all layer boundaries- [ ] Defined format at each boundary- [ ] Decided where validation happens
After implementation:- [ ] Tested with edge cases (null, empty, invalid)- [ ] Verified error handling at each boundary- [ ] Checked data survives round-trip
---
## When to Create Flow Documentation
Create detailed flow docs when:- Feature spans 3+ layers- Multiple teams are involved- Data format is complex- Feature has caused bugs before12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# Thinking Guides
> **Purpose**: Expand your thinking to catch things you might not have considered.
---
## Why Thinking Guides?
**Most bugs and tech debt come from "didn't think of that"**, not from lack of skill:
- Didn't think about what happens at layer boundaries → cross-layer bugs- Didn't think about code patterns repeating → duplicated code everywhere- Didn't think about edge cases → runtime errors- Didn't think about future maintainers → unreadable code
These guides help you **ask the right questions before coding**.
---
## Available Guides
| Guide | Purpose | When to Use ||-------|---------|-------------|| [Code Reuse Thinking Guide](./code-reuse-thinking-guide.md) | Identify patterns and reduce duplication | When you notice repeated patterns || [Cross-Layer Thinking Guide](./cross-layer-thinking-guide.md) | Think through data flow across layers | Features spanning multiple layers |
---
## Quick Reference: Thinking Triggers
### When to Think About Cross-Layer Issues
- [ ] Feature touches 3+ layers (API, Service, Component, Database)- [ ] Data format changes between layers- [ ] Multiple consumers need the same data- [ ] You're not sure where to put some logic
→ Read [Cross-Layer Thinking Guide](./cross-layer-thinking-guide.md)
### When to Think About Code Reuse
- [ ] You're writing similar code to something that exists- [ ] You see the same pattern repeated 3+ times- [ ] You're adding a new field to multiple places- [ ] **You're modifying any constant or config**- [ ] **You're creating a new utility/helper function** ← Search first!
→ Read [Code Reuse Thinking Guide](./code-reuse-thinking-guide.md)
---
## Pre-Modification Rule (CRITICAL)
> **Before changing ANY value, ALWAYS search first!**
```bash# Search for the value you're about to changegrep -r "value_to_change" .```
This single habit prevents most "forgot to update X" bugs.
---
## How to Use This Directory
1. **Before coding**: Skim the relevant thinking guide2. **During coding**: If something feels repetitive or complex, check the guides3. **After bugs**: Add new insights to the relevant guide (learn from mistakes)
---
## Contributing
Found a new "didn't think of that" moment? Add it to the relevant guide.
---
**Core Principle**: 30 minutes of thinking saves 3 hours of debugging.123456789101112131415161718192021222324252627282930{"file":"prompts/0515/prd.md","reason":"Check implementation against accepted scope and acceptance criteria"}{"file":"prompts/0515/spec.md","reason":"Check free registration protection and migration constraints"}{"file":"prompts/0515/implementation-plan.md","reason":"Check staged verification requirements"}{"file":".trellis/spec/backend/quality-guidelines.md","reason":"Quality gate context"}{"file":".trellis/spec/backend/error-handling.md","reason":"Error-handling and fallback review context"}{"file":".trellis/spec/backend/logging-guidelines.md","reason":"Runtime logging review context"}{"file":".trellis/spec/guides/cross-layer-thinking-guide.md","reason":"Cross-layer consistency review"}{"command":"python -m pytest tests/integration/test_docker_guard.py tests/unit/test_runtime_resources.py tests/unit/test_api_playwright_cleanup.py","result":"pass","evidence":"20 passed, 1 warning","reason":"Verify Docker guard contracts, runtime resource helpers, and Playwright cleanup regressions after Windows/Git Bash entrypoint syntax test fix"}{"command":"docker build -f Dockerfile.fast --build-arg GIT_SHA=0515-hardening --build-arg BUILD_TIME=2026-05-15T00:00:00Z -t autoteam:fast-0515 .","result":"pass","evidence":"Image autoteam:fast-0515 built successfully from autoteam:latest with updated entrypoint copied and CRLF-normalized","reason":"Verify fast Docker image path remains buildable after hardening changes"}{"command":"docker run --rm autoteam:fast-0515 status","result":"pass","evidence":"self-check OK: 13 critical symbols imported; self-check passed; subsequent warnings were expected missing local .env settings","reason":"Verify real container entrypoint self-check and heredoc syntax"}{"command":"python -m pytest tests/unit/test_round11_personal_oauth_retry.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round12_s4_register_dual_path.py tests/unit/test_manager_fill.py","result":"pass","evidence":"58 passed","reason":"Protect free account registration and personal OAuth retry/token injection flows"}{"command":"python -m pytest tests/unit/test_api_status.py tests/unit/test_playwright_guard.py tests/static/test_playwright_hygiene.py tests/unit/test_round12_rotate_sse_stream.py","result":"pass","evidence":"15 passed, 1 warning","reason":"Verify API status runtime_resources exposure, Playwright guard/hygiene, and rotate SSE behavior"}{"command":"python -m ruff check src","result":"pass","evidence":"All checks passed","reason":"Verify source lint remains clean"}{"command":"python -m ruff check src/autoteam/runtime_resources.py src/autoteam/playwright_lifecycle.py src/autoteam/chatgpt_api.py src/autoteam/api.py tests/unit/test_runtime_resources.py tests/unit/test_api_playwright_cleanup.py tests/integration/test_docker_guard.py","result":"pass","evidence":"All checks passed","reason":"Verify changed files lint clean"}{"command":"docker compose config","result":"pass","evidence":"Compose parsed init=true, mem_limit=2g, memswap_limit=2g, pids_limit=768, shm_size=1gb, healthcheck=/api/version","reason":"Verify Docker compose resource and healthcheck settings are syntactically valid"}{"command":"python -m ruff check src tests","result":"known-fail-unrelated","evidence":"Existing tests/unit/test_round12_wireup.py import-order/unused-variable/unused-import issues; changed files and src lint pass","reason":"Document full lint state without modifying unrelated WIP"}{"command":"python -m pytest tests/unit/test_chatgpt_transport.py tests/unit/test_round11_api_fetch_header_sanitize.py tests/unit/test_api_playwright_cleanup.py tests/integration/test_docker_guard.py tests/unit/test_runtime_resources.py","result":"pass","evidence":"32 passed, 1 warning","reason":"Verify opt-in transport, Round 11 header sanitize compatibility, Playwright cleanup, Docker guard, and runtime resources after final absorption"}{"command":"python -m pytest tests/unit/test_round11_personal_oauth_retry.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round12_s4_register_dual_path.py tests/unit/test_manager_fill.py","result":"pass","evidence":"58 passed","reason":"Final free account registration protection regression after transport/probe absorption"}{"command":"python -m pytest tests/unit/test_api_status.py tests/unit/test_playwright_guard.py tests/static/test_playwright_hygiene.py tests/unit/test_round12_rotate_sse_stream.py","result":"pass","evidence":"15 passed, 1 warning","reason":"Final API/status/Playwright/SSE regression after transport/probe absorption"}{"command":"python -m ruff check src/autoteam/chatgpt_transport.py src/autoteam/playwright_probe.py src/autoteam/config.py src/autoteam/chatgpt_api.py src/autoteam/api.py tests/unit/test_chatgpt_transport.py tests/unit/test_api_playwright_cleanup.py tests/integration/test_docker_guard.py","result":"pass","evidence":"All checks passed","reason":"Final targeted lint for all newly absorbed transport/probe and touched integration code"}{"command":"python -m ruff check src","result":"pass","evidence":"All checks passed","reason":"Final source lint"}{"command":"docker build -f Dockerfile.fast --build-arg GIT_SHA=0515-hardening --build-arg BUILD_TIME=2026-05-15T00:00:00Z -t autoteam:fast-0515 .","result":"pass","evidence":"Image autoteam:fast-0515 rebuilt successfully with curl-cffi dependency from uv.lock","reason":"Final fast Docker build after dependency and entrypoint changes"}{"command":"docker run --rm autoteam:fast-0515 status","result":"pass","evidence":"self-check OK: 15 critical symbols imported; self-check passed; subsequent warnings were expected missing local .env settings","reason":"Final real container entrypoint self-check"}{"file":"prompts/0515/autoteam1-absorption-audit.md","result":"pass","evidence":"Checklist maps autoteam-1 designs to absorbed/superseded/rejected current artifacts","reason":"Completion audit against expanded objective"}{"file":".trellis/spec/backend/runtime-docker-hardening.md","result":"pass","evidence":"New backend code-spec captures the 7-section Docker/runtime/transport contract required for future changes","reason":"Spec update after infra/runtime hardening task"}{"file":".trellis/spec/backend/free-registration-hardening.md","result":"pass","evidence":"Round 2 backend code-spec captures fill-personal safety boundary, Team-seat preflight, and SignupProfile consistency","reason":"Spec update after free registration hardening task"}{"command":"python -m ruff check src tests","result":"pass","evidence":"All checks passed","reason":"Deep review cleanup: fixed prior test_round12_wireup lint failures and rechecked all source/tests"}{"command":"python -m pytest tests/unit","result":"pass","evidence":"736 passed, 1 warning","reason":"Full unit regression after autoteam-1 transport default alignment, OAuth require_browser fix, and manager HTTP-transport lifecycle cleanup"}{"command":"python -m pytest tests/integration/test_docker_guard.py","result":"pass","evidence":"13 passed, 1 warning","reason":"Docker/runtime contract regression after transport default and lifecycle cleanup"}{"command":"docker compose config >/tmp/autoteam-compose-config.txt","result":"pass","evidence":"compose_config_ok","reason":"Compose syntax/config verification after Docker runtime bounds and CHATGPT_API_TRANSPORT=auto documentation update"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# Completion Audit - 2026-05-15
## Objective
Continue until the useful and outstanding designs from `D:\Desktop\autoteam-1` are fully absorbed into `D:\Desktop\AutoTeam`, especially hardening, stability, overflow/resource containment, and Docker deployment, while confirming that the free-account registration main flow is not broken.
## Success Criteria
1. Planning artifacts exist under `prompts/0515` before implementation.2. Source designs from `D:\Desktop\autoteam-1\AutoTeam` are classified as absorbed, replaced by a stronger current implementation, or explicitly rejected with a reason.3. Docker deployment has concrete resource boundaries, healthcheck, fast image path, and startup self-check.4. Runtime resource and Playwright lifecycle hardening are implemented and covered by tests.5. Optional HTTP transport is opt-in and cannot default-change free registration/OAuth behavior.6. Free registration Round 11/12 regressions pass.7. Verification uses real commands, not only a checklist.
## Prompt-to-Artifact Checklist
| Requirement | Evidence | Verdict || --- | --- | --- || Write PRD/spec/plan first under `prompts/0515` | `prompts/0515/prd.md`, `spec.md`, `implementation-plan.md`, `research-docker-playwright-hardening.md`, `autoteam1-absorption-audit.md` exist and define the safe absorption plan | Pass || Map source designs to decisions | `prompts/0515/autoteam1-absorption-audit.md` classifies Docker, runtime resources, Playwright lifecycle, probe, transport, mail/provider, CPA, Sub2API/sync-target, old manager/codex_auth/invite, generated artifacts, and codex-watchdog | Pass || Absorb Docker resource boundaries | `docker-compose.yml` has `init: true`, `shm_size: "1gb"`, `mem_limit: "2g"`, `memswap_limit: "2g"`, `pids_limit: 768`, resource warning env vars, and `/api/version` healthcheck | Pass || Keep build identity and self-check | `Dockerfile.fast` keeps `GIT_SHA`/`BUILD_TIME`, OCI labels, and `docker-entrypoint.sh`; entrypoint imports 15 critical symbols and exits on self-check failure | Pass || Add runtime resource hardening | `src/autoteam/runtime_resources.py` reads `/proc/self/status`, cgroup memory/pids, browser process live/zombie counts, warns and runs `gc.collect()` above threshold | Pass || Expose resource snapshot safely | `/api/status` returns `runtime_resources`; `_auto_check_loop()` logs `log_runtime_resource_snapshot(...)` | Pass || Add Playwright cleanup | `src/autoteam/playwright_lifecycle.py` closes page -> context -> browser -> playwright; `ChatGPTTeamAPI._launch_browser()` calls `stop()` on partial init failure; `stop()` clears fields | Pass || Isolate background Team count probe | `src/autoteam/playwright_probe.py` provides `team-member-count`; `src/autoteam/api.py` runs it in a subprocess with timeout and process-group kill fallback | Pass || Add opt-in transport only | `.env.example` and `src/autoteam/config.py` default `CHATGPT_API_TRANSPORT=playwright`; `src/autoteam/chatgpt_transport.py` is used only when configured and falls back on missing dependency/init errors/challenge/auth anomalies | Pass || Preserve free registration main flow | `FillParams.leave_workspace`, `fill-personal`, `cmd_fill(..., leave_workspace=True)`, `_run_post_register_oauth(..., leave_workspace=True)`, `plan_type=free`, `STATUS_PERSONAL`, plan drift and failure recording remain in the Round 11/12 path | Pass || Avoid unsafe source overwrite | Old source `manager.py`, `codex_auth.py`, `invite.py` were not copied over the current Round 11/12 implementations | Pass || Treat stronger current implementations correctly | Source `cloudflare_temp_email.py` / `mail_provider.py` are replaced by current `src/autoteam/mail/*`; source `sub2api_sync.py` / `sync_targets.py` are explicitly out of this hardening/Docker scope and recorded as a later standalone candidate | Pass |
## Verification Rerun
- `python -m pytest tests/unit/test_chatgpt_transport.py tests/unit/test_round11_api_fetch_header_sanitize.py tests/unit/test_api_playwright_cleanup.py tests/integration/test_docker_guard.py tests/unit/test_runtime_resources.py` -> `32 passed, 1 warning`- `python -m pytest tests/unit/test_round11_personal_oauth_retry.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round12_s4_register_dual_path.py tests/unit/test_manager_fill.py` -> `58 passed`- `python -m pytest tests/unit/test_api_status.py tests/unit/test_playwright_guard.py tests/static/test_playwright_hygiene.py tests/unit/test_round12_rotate_sse_stream.py` -> `15 passed, 1 warning`- `python -m ruff check src` -> `All checks passed!`- Targeted ruff for changed code/tests -> `All checks passed!`- `docker compose config` -> parses `init: true`, `mem_limit: 2147483648`, `memswap_limit: 2147483648`, `pids_limit: 768`, `shm_size: 1073741824`, and `/api/version` healthcheck- `docker image inspect autoteam:fast-0515` -> label revision `0515-hardening`, created `2026-05-15T00:00:00Z`- `docker run --rm autoteam:fast-0515 status` -> `[self-check] OK: 15 critical symbols imported.` and `[self-check] passed.`- `python -m ruff check src tests` -> still fails only in pre-existing `tests/unit/test_round12_wireup.py` with import sorting, unused variables/import, and B009; this is outside this task's touched files and was not fixed here.- `.trellis/spec/backend/runtime-docker-hardening.md` -> added as the reusable backend code-spec for this Docker/runtime/transport contract- `.trellis/tasks/05-15-autoteam1-hardening-docker-apply/check.jsonl` -> valid JSONL, 25 lines- `.trellis/tasks/05-15-autoteam1-hardening-docker-apply/implement.jsonl` -> valid JSONL, 10 lines
## Conclusion
The hardening, stability, overflow/resource-containment, Docker deployment, killable Playwright probe, Playwright lifecycle cleanup, and opt-in transport designs from `D:\Desktop\autoteam-1` have been absorbed or replaced by stronger current implementations. The remaining source-only modules are either generated/runtime artifacts, already covered by the current stronger mail/registration stack, or unrelated product integrations that should not be mixed into this safety-focused task. The free-account registration main flow is protected by the Round 11/12 regression set and remains on the default Playwright path.
No implementation work remains for this objective. The Trellis task has not been archived or committed because the worktree contains unrelated dirty/untracked files and the user did not request a commit.12345678910111213141516171819202122232425262728293031323334353637# Free Registration Round 2 Completion Audit
## Objective
Critically compare `D:\Desktop\autoteam-1\AutoTeam` and `D:\Desktop\AutoTeam` with the former as the mother template, then add another safety-focused hardening round for the free-account registration main flow.
## Safety Boundary
This round deliberately does not add bypasses for captcha, human verification, platform restrictions, rate limits, or anti-abuse systems. The accepted hardening scope is data consistency, local/remote state consistency, early rejection of unsafe tasks, auditability, and tests.
## Prompt-to-Artifact Checklist
| Requirement | Evidence | Verdict || --- | --- | --- || Critically compare both projects with `autoteam-1` as template | `prompts/0515/free-registration-round2-critical-audit.md` compares manager/codex_auth/invite/signup_profile/accounts/cpa/mail dimensions | Pass || Preserve free registration main flow | No change to `_run_post_register_oauth(..., leave_workspace=True)`, Personal OAuth retry count, `plan_type=free`, or `STATUS_PERSONAL` semantics | Pass || Absorb mother-template profile consistency | `src/autoteam/signup_profile.py` now derives `age` from generated birthday and validates age range while preserving current `SignupProfile` field shape | Pass || Align API and manager Team-seat preflight | `src/autoteam/api.py:post_fill()` now uses `manager._count_local_team_seat_accounts(load_accounts())`, so `STATUS_AUTH_INVALID` contributes to the fill-personal hard cap | Pass || Add regression coverage | `tests/unit/test_round12_s3_cherry_pick.py` checks age/birthday consistency; `tests/unit/test_free_registration_hardening.py` checks API 409 when seats include auth_invalid | Pass || Preserve documented contract | `.trellis/spec/backend/free-registration-hardening.md` added and indexed | Pass |
## Verification
- `python -m pytest tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_free_registration_hardening.py` -> `45 passed, 1 warning`- `python -m ruff check src/autoteam/signup_profile.py src/autoteam/api.py tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_free_registration_hardening.py` -> `All checks passed!`- `python -m pytest tests/unit/test_round11_personal_oauth_retry.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round12_s4_register_dual_path.py tests/unit/test_manager_fill.py` -> `58 passed`- `python -m pytest tests/unit/test_chatgpt_transport.py tests/unit/test_api_playwright_cleanup.py tests/unit/test_runtime_resources.py tests/integration/test_docker_guard.py` -> `28 passed, 1 warning`- `python -m pytest tests/unit/test_round8_integration.py tests/unit/test_api_status.py tests/unit/test_round12_rotate_sse_stream.py` -> `22 passed, 1 warning`- `python -m ruff check src` -> `All checks passed!`
## Known Non-Blocking State
The repository still has unrelated dirty/untracked files and the known full-suite `ruff src tests` failure in `tests/unit/test_round12_wireup.py` from earlier work. This round does not modify that unrelated WIP.
## Conclusion
Round 2 is complete. The mother-template comparison produced two safe, concrete hardening changes: signup profile age/birthday consistency and API/manager Team-seat preflight alignment. The free registration main flow remains unchanged beyond earlier unsafe-task rejection and consistency safeguards.1234567891011121314{"file":"prompts/0515/prd.md","reason":"User-requested authoritative PRD and scope boundaries for this implementation"}{"file":"prompts/0515/spec.md","reason":"User-requested implementation contract, including free registration protection rules"}{"file":"prompts/0515/implementation-plan.md","reason":"Staged execution checklist and validation plan"}{"file":"prompts/0515/research-docker-playwright-hardening.md","reason":"External and local research grounding Docker/Playwright choices"}{"file":".trellis/spec/backend/index.md","reason":"Backend spec index for project conventions"}{"file":".trellis/spec/backend/quality-guidelines.md","reason":"Quality gate context for implementation"}{"file":".trellis/spec/backend/error-handling.md","reason":"Error-handling context for cleanup and fallback behavior"}{"file":".trellis/spec/backend/logging-guidelines.md","reason":"Logging context for runtime resource warnings"}{"file":".trellis/spec/guides/cross-layer-thinking-guide.md","reason":"Cross-layer impact guide for Docker/API/runtime changes"}{"file":".trellis/spec/backend/runtime-docker-hardening.md","reason":"Executable backend contract for Docker bounds, Playwright cleanup, resource probes, and transport safety"}{"file":".trellis/spec/backend/free-registration-hardening.md","reason":"Executable backend contract for fill-personal safety, Team-seat preflight, and SignupProfile consistency"}{"file":"src/autoteam/codex_auth.py","reason":"Deep review fix: SessionCodexAuthFlow now matches autoteam-1 and forces require_browser=True so CHATGPT_API_TRANSPORT=auto cannot break OAuth browser context"}{"file":"src/autoteam/manager.py","reason":"Deep review fix: Team API lifecycle checks now use _chatgpt_session_ready/is_started semantics so HTTP-only auto transport sessions are reused and stopped instead of leaking behind browser-only guards"}{"file":"src/autoteam/chatgpt_transport.py","reason":"Deep review fix: __Secure session cookies are set with secure=True to avoid curl_cffi warning and keep cookie semantics explicit"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# Apply autoteam-1 hardening and Docker deployment features
## Goal
Apply selected stability, overflow-prevention, and Docker deployment hardening from `D:\Desktop\autoteam-1` to the current `D:\Desktop\AutoTeam` project, while preserving the current free-account registration flow.
## Authoritative Planning Docs
- `prompts/0515/prd.md`- `prompts/0515/spec.md`- `prompts/0515/implementation-plan.md`- `prompts/0515/research-docker-playwright-hardening.md`
## What I Already Know
- Current AutoTeam already contains newer Round 11/12 free registration protections: `leave_workspace=True`, Personal OAuth retry, plan drift recording, workspace pool, register dual path, master health checks, and related tests.- `D:\Desktop\autoteam-1\AutoTeam` contributes useful low-coupling hardening: Docker resource boundaries, `runtime_resources.py`, `playwright_lifecycle.py`, `Dockerfile.fast`, and optional `chatgpt_transport.py`.- `D:\Desktop\autoteam-1\codex-watchdog` history warns that automation safety must be conservative and dry-run verifiable.
## Requirements
- Preserve current free-account registration semantics and tests.- Add Docker/Compose hardening without removing existing build fingerprint and entrypoint self-check contracts.- Add runtime resource probes and Playwright lifecycle cleanup with unit coverage.- Keep `curl_cffi` transport out of the first implementation round unless explicitly approved later.
## Acceptance Criteria
- [ ] `prompts/0515` docs are present and accepted before implementation.- [ ] Docker compose has init, shm, memory/PID boundaries, resource env vars, and healthcheck.- [ ] Runtime resource probe gracefully handles missing cgroup/proc files.- [ ] Playwright cleanup is idempotent and cleans partially initialized browser sessions.- [ ] Free registration regression tests pass.- [ ] Docker guard and relevant unit tests pass.
## Out of Scope
- Rewriting free registration.- Directly overwriting current manager/codex OAuth code with older `autoteam-1` files.- Enabling optional HTTP transport by default in the first round.
## Research References
- `research/docker-playwright-hardening.md`
## Technical Approach
Use a staged implementation:
1. Docker/Compose hardening.2. Runtime resource and Playwright lifecycle hardening.3. Free registration regression verification.4. Optional transport evaluation as a separate later stage.
## Definition of Done
- Tests added/updated where behavior changes.- Lint/static checks pass.- Docker config validates.- No unverified claim of Docker runtime success without a real command result.- Docs updated with rollout and rollback notes.
123456789101112131415161718192021222324# Research: Docker and Playwright hardening for AutoTeam
## Sources
- Docker Compose services reference: <https://docs.docker.com/reference/compose-file/services/>- Docker Compose deploy resources reference: <https://docs.docker.com/reference/compose-file/deploy/#resources>- Playwright Python Docker guide: <https://playwright.dev/python/docs/docker>- Playwright Docker guide: <https://playwright.dev/docs/docker>
## Takeaways
- `init: true` is appropriate for a long-running service that starts browser subprocesses because it helps signal handling and zombie reaping.- Chromium is sensitive to Docker shared-memory defaults. Playwright recommends host IPC in some workflows; for this project, `shm_size: "1gb"` is the safer compose default because it improves stability without broadening IPC isolation.- Health checks should hit a real low-cost endpoint. The current project already has `/api/version`, so use it instead of process-only checks.- Resource boundaries should prevent browser and task growth from consuming the host. Compose-level memory and PID limits plus runtime cgroup probes are both useful.- Current AutoTeam already has Docker build args, OCI labels, and entrypoint self-checks. Any `Dockerfile.fast` imported from `autoteam-1` must preserve those contracts.
## Local mapping
- Use `D:\Desktop\autoteam-1\AutoTeam\docker-compose.yml` as a reference for `init`, `shm_size`, memory/PID limits, and resource env vars.- Use `D:\Desktop\autoteam-1\AutoTeam\src\autoteam\runtime_resources.py` as the reference implementation for cgroup and zombie probes.- Use `D:\Desktop\autoteam-1\AutoTeam\src\autoteam\playwright_lifecycle.py` as the reference implementation for cleanup ordering.- Do not import old registration logic over current Round 11/12 free registration code.
1234567891011121314151617181920212223242526{ "id": "autoteam1-hardening-docker-apply", "name": "autoteam1-hardening-docker-apply", "title": "brainstorm: apply autoteam-1 hardening and docker deployment", "description": "", "status": "in_progress", "dev_type": null, "scope": null, "package": null, "priority": "P2", "creator": "ZRainbow", "assignee": "ZRainbow", "createdAt": "2026-05-15", "completedAt": null, "branch": null, "base_branch": "main", "worktree_path": null, "commit": null, "pr_url": null, "subtasks": [], "children": [], "parent": null, "relatedFiles": [], "notes": "", "meta": {}}1234567891011121314151617181920212223242526272829# Incremental build: reuse the stable image with system deps, uv, and Playwright Chromium.FROM autoteam:latest
WORKDIR /app
ARG GIT_SHA=unknownARG BUILD_TIME=unknownLABEL org.opencontainers.image.revision="${GIT_SHA}"LABEL org.opencontainers.image.created="${BUILD_TIME}"ENV AUTOTEAM_GIT_SHA="${GIT_SHA}"ENV AUTOTEAM_BUILD_TIME="${BUILD_TIME}"
# Update Python dependencies only when the lockfile or project metadata changes.COPY pyproject.toml uv.lock ./RUN uv sync --no-dev
# Overlay the latest app code.COPY src/ src/COPY web/ web/
# Preserve the regular entrypoint self-check and make the script Linux-safe.COPY docker-entrypoint.sh /docker-entrypoint.shRUN sed -i 's/\r$//' /docker-entrypoint.sh && chmod +x /docker-entrypoint.sh
ENV DISPLAY=:99EXPOSE 8787
ENTRYPOINT ["/docker-entrypoint.sh"]CMD ["api"]4 unmodified lines567891011124 unmodified linesargs:GIT_SHA: ${GIT_SHA:-unknown}BUILD_TIME: ${BUILD_TIME:-unknown}ports:- "8787:8787"volumes:- ./data:/app/datarestart: unless-stopped4 unmodified lines567891011121314151617181920212223242526274 unmodified linesargs:GIT_SHA: ${GIT_SHA:-unknown}BUILD_TIME: ${BUILD_TIME:-unknown}init: trueshm_size: "1gb"mem_limit: "2g"memswap_limit: "2g"pids_limit: 768environment:MALLOC_ARENA_MAX: "2"AUTOTEAM_MEMORY_WARN_RATIO: "0.85"AUTOTEAM_ZOMBIE_WARN_THRESHOLD: "5"ports:- "8787:8787"volumes:- ./data:/app/datahealthcheck:test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8787/api/version >/dev/null"]interval: 30stimeout: 10sretries: 3start_period: 45srestart: unless-stopped
28 unmodified lines293031323334353637383940414215 unmodified lines58596061626364656628 unmodified lines# Self-check: 关键 import 白名单 — 失败即 crash-loop(SPEC-3 §2)# ---------------------------------------------------------------------------echo "[self-check] verifying critical imports..."uv run python - <<'PYEOF' || {echo "[self-check] FATAL: critical import failed - image is likely stale or broken." >&2echo "[self-check] If you just pulled new code, the image must be rebuilt:" >&2echo "[self-check] docker compose down" >&2echo "[self-check] docker compose build --no-cache --build-arg GIT_SHA=\$(git rev-parse --short HEAD)" >&2echo "[self-check] docker compose up -d" >&2exit 1}import sys# 核心 web 应用入口15 unmodified lines# manager → accounts 链路(覆盖跨模块 typo)from autoteam.manager import sync_account_states # noqa: F401print("[self-check] OK: %d critical symbols imported." % 11)sys.exit(0)PYEOFecho "[self-check] passed."# 执行命令28 unmodified lines2930313233343515 unmodified lines515253545556575859606162636465666768697071727328 unmodified lines# Self-check: 关键 import 白名单 — 失败即 crash-loop(SPEC-3 §2)# ---------------------------------------------------------------------------echo "[self-check] verifying critical imports..."if ! uv run python - <<'PYEOF'import sys# 核心 web 应用入口15 unmodified lines# manager → accounts 链路(覆盖跨模块 typo)from autoteam.manager import sync_account_states # noqa: F401# 0515 runtime hardening helpersfrom autoteam.runtime_resources import collect_runtime_resource_snapshot # noqa: F401from autoteam.playwright_lifecycle import close_playwright_objects # noqa: F401from autoteam.playwright_probe import main as playwright_probe_main # noqa: F401from autoteam.chatgpt_transport import build_chatgpt_transport # noqa: F401print("[self-check] OK: %d critical symbols imported." % 15)sys.exit(0)PYEOFthenecho "[self-check] FATAL: critical import failed - image is likely stale or broken." >&2echo "[self-check] If you just pulled new code, the image must be rebuilt:" >&2echo "[self-check] docker compose down" >&2echo "[self-check] docker compose build --no-cache --build-arg GIT_SHA=\$(git rev-parse --short HEAD)" >&2echo "[self-check] docker compose up -d" >&2exit 1fiecho "[self-check] passed."# 执行命令
20 unmodified lines21222324252617 unmodified lines44454647484933 unmodified lines83848586878869 unmodified lines15815916016116216316420 unmodified linesdocker compose down```## 数据持久化所有运行数据都存储在 `data/` 目录,通过 volume 挂载到容器:17 unmodified linesdocker run -d -p 8787:8787 -v $(pwd)/data:/app/data autoteam```## 配置方式### 方式一:预先编辑 `.env`33 unmodified lines通常是:- 配置缺失- CloudMail / CPA 连通性验证失败### `data` 目录没有写权限69 unmodified linesdocker compose logs autoteam | head -20# 期望看到:# [self-check] verifying critical imports...# [self-check] OK: 11 critical symbols imported.# [self-check] passed.```20 unmodified lines212223242526272829303132333435363738394017 unmodified lines58596061626364656667686970717273747576777879808133 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713869 unmodified lines20820921021121221321420 unmodified linesdocker compose down```当前 `docker-compose.yml` 默认启用以下运行时加固:- `init: true`:容器内启用 init/reaper,帮助回收 Chromium / Playwright 子进程。- `shm_size: "1gb"`:提高 `/dev/shm`,降低 Chromium 在 Docker 默认 64MB shm 下崩溃的概率。- `mem_limit: "2g"` / `pids_limit: 768`:给浏览器和后台任务设置硬边界,避免异常增长拖垮宿主机。- `healthcheck`:通过 `http://127.0.0.1:8787/api/version` 检查真实 API 可用性。- `AUTOTEAM_MEMORY_WARN_RATIO` / `AUTOTEAM_ZOMBIE_WARN_THRESHOLD`:控制运行时资源告警阈值。运行时默认启用与 `autoteam-1` 对齐的轻量 Team API transport:- 默认 `CHATGPT_API_TRANSPORT=auto`,Team backend API 读取会先尝试 HTTP transport;如果返回 Cloudflare/HTML/challenge 或鉴权异常,会回退 Playwright。- 显式设置 `CHATGPT_API_TRANSPORT=playwright` 时,可强制恢复旧的浏览器上下文 fetch 行为。- 该选项只影响管理员 Team API 读写;free 帐号注册、Personal OAuth、验证码、workspace UI 选择必须继续强制真实浏览器上下文。## 数据持久化所有运行数据都存储在 `data/` 目录,通过 volume 挂载到容器:17 unmodified linesdocker run -d -p 8787:8787 -v $(pwd)/data:/app/data autoteam```### 快速增量镜像首次完整构建后,本仓库提供 `Dockerfile.fast` 用于本地快速迭代。它复用 `autoteam:latest` 中已经安装好的系统依赖、uv 和 Playwright Chromium,只覆盖 Python 依赖与源码。```bash# 先确保有稳定基础镜像GIT_SHA=$(git rev-parse --short HEAD) \BUILD_TIME=$(date -u +%FT%TZ) \docker build -t autoteam:latest .# 后续本地快速迭代GIT_SHA=$(git rev-parse --short HEAD) \BUILD_TIME=$(date -u +%FT%TZ) \docker build -f Dockerfile.fast -t autoteam:fast .````Dockerfile.fast` 仅用于开发迭代,不替代首次完整构建;如果系统依赖、Playwright 版本、基础镜像或 `uv.lock` 出现难以解释的问题,回到标准 `Dockerfile` 做 `--no-cache` 构建。## 配置方式### 方式一:预先编辑 `.env`33 unmodified lines通常是:- 配置缺失- CloudMail / CPA 连通性验证失败- entrypoint self-check 发现镜像代码与契约符号不一致- `/api/version` healthcheck 持续失败查看健康状态:```bashdocker compose psdocker inspect --format '{{json .State.Health}}' autoteam-autoteam-1 | python -m json.tool```查看资源占用和 PID 数:```bashdocker statsdocker compose top```如果日志出现 `[资源] ... browser zombie processes=...`,优先确认 compose 中 `init: true` 仍然存在;如果出现 memory usage warning,先减少并发注册/轮转,再考虑调大 `mem_limit`。### `data` 目录没有写权限69 unmodified linesdocker compose logs autoteam | head -20# 期望看到:# [self-check] verifying critical imports...# [self-check] OK: 15 critical symbols imported.# [self-check] passed.```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# 0515 吸收完成审计:autoteam-1 突出设计到当前项目
## 目标重述
在 `D:\Desktop\AutoTeam` 中,以 `D:\Desktop\autoteam-1` 为参考来源,完整吸收其中适合当前项目的优秀设计:加固、稳定、防止资源/进程溢出、Docker 部署和低风险性能增强;同时不破坏 free 帐号注册主流程。
完成标准不是“文件相似”,而是每个源端突出设计都必须落到以下三种结论之一:
- 已吸收:当前项目已有对应 artifact、测试或运行证据。- 已被当前更强实现替代:源端设计价值存在,但当前项目已有更新、更完整且经过测试的实现。- 明确不吸收:源端内容不是设计能力、会降级当前 Round 11/12 主流程,或属于独立工具边界。
## prompt-to-artifact checklist
| 要求 / 源端设计 | 当前结论 | 证据 || --- | --- | --- || 先写 PRD/spec/计划到 `prompts/0515` | 已完成 | `prd.md`、`spec.md`、`implementation-plan.md`、`research-docker-playwright-hardening.md`、本审计文件 || Docker compose 资源边界:`init`、`shm_size`、内存、PID、healthcheck | 已吸收 | `docker-compose.yml`;`docker compose config` 通过并解析出 `init: true`、`mem_limit=2g`、`pids_limit=768`、`shm_size=1gb` || `Dockerfile.fast` 快速增量镜像 | 已吸收 | `Dockerfile.fast`;`docker build -f Dockerfile.fast ... -t autoteam:fast-0515 .` 通过 || entrypoint self-check 保持真实启动守卫 | 已增强 | `docker-entrypoint.sh` self-check 扩展到 `15 critical symbols`;`docker run --rm autoteam:fast-0515 status` 通过 || cgroup memory/pids/browser zombie 资源探针 | 已吸收 | `src/autoteam/runtime_resources.py`;`tests/unit/test_runtime_resources.py` || 自动巡检资源告警,不阻塞业务 | 已吸收 | `api.py:_auto_check_loop()` 调用 `log_runtime_resource_snapshot(logger, label="auto-check")` || `/api/status` 暴露资源快照 | 已吸收 | `api.py:get_status()` 返回 `runtime_resources`;`tests/unit/test_api_status.py` 通过 || Playwright 统一 close 顺序和幂等 cleanup | 已吸收 | `src/autoteam/playwright_lifecycle.py`;`ChatGPTTeamAPI.stop()`;`tests/unit/test_api_playwright_cleanup.py` || `_launch_browser()` 半初始化失败清理 | 已吸收 | `ChatGPTTeamAPI._launch_browser()` 失败时 `self.stop()`;目标测试覆盖 || API 失败路径释放 `ChatGPTTeamAPI` | 已吸收 | `post_admin_login_start()`、`get_team_members()`、kick/remove 路径的 `try/finally`;目标测试覆盖 || killable Playwright probe 防卡死/溢出 | 已吸收 | `src/autoteam/playwright_probe.py`;`api.py:_run_playwright_probe()` 超时 kill group;目标测试覆盖 || `curl_cffi` Team API transport | 已按母板默认吸收 | `src/autoteam/chatgpt_transport.py`、`pyproject.toml`、`uv.lock`、`.env.example`;默认 `CHATGPT_API_TRANSPORT=auto`,OAuth/UI 路径用 `require_browser=True` 隔离 || transport 回退 Playwright | 已吸收 | `_transport_response_requires_browser_fallback()`、`_direct_api_fetch()`;`tests/unit/test_chatgpt_transport.py` || free 注册主流程不破坏 | 已验证 | Round 11/12 free 注册保护回归 `58 passed` || Round 11 header sanitize 不被 transport 改坏 | 已验证 | `tests/unit/test_round11_api_fetch_header_sanitize.py` 通过 || Cloudflare Temp Email / mail provider 设计 | 当前更强实现替代 | 当前 `src/autoteam/mail/` 已有 `MailProvider` 抽象、`cf_temp_email`、`maillab`、fallback、probe 和更多单测;不回贴源端旧 `mail_provider.py` / `cloudflare_temp_email.py` || signup profile / OAuth failure recovery | 当前更强实现替代 | 当前 `manager.py` / `codex_auth.py` 已有 Round 11/12 Personal OAuth retry、plan drift、workspace pool、register dual path;free 注册回归覆盖 || CPA 同步保护 | 当前更强实现替代 | 当前 `cpa_sync.py` 已包含 active+personal 同步、token 删除守卫、workspace summary,比源端旧 active-only/disabled 逻辑更贴合当前 personal/free 路径 || Sub2API / sync target 分发 | 明确不吸收进本任务代码 | 属于新外部产品集成,不是本次加固/稳定/Docker主线;源端实现依赖旧 config/UI/manager 路径,直接引入会扩大 blast radius。已在审计中记录为后续独立任务候选,不影响当前目标的“稳定性突出设计”吸收 || 旧 `manager.py` / `codex_auth.py` / `invite.py` 覆盖 | 明确拒绝 | PRD/spec 红线;当前 Round 11/12 版本优先,回归通过 || `autoteam-1` 中 data/auths/screenshots/dist/pycache | 明确不吸收 | 运行产物和构建产物,不是设计能力 || `codex-watchdog` 独立工具经验 | 已吸收为原则,不迁入 app | 保守自动化、避免误扰动活跃会话的原则写入 PRD;该工具不属于当前 AutoTeam app 代码范围 |
## 实际验证
已通过:
- `python -m pytest tests/unit/test_chatgpt_transport.py tests/unit/test_round11_api_fetch_header_sanitize.py tests/unit/test_api_playwright_cleanup.py tests/integration/test_docker_guard.py tests/unit/test_runtime_resources.py` -> `32 passed, 1 warning`- `python -m pytest tests/unit/test_round11_personal_oauth_retry.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round12_s4_register_dual_path.py tests/unit/test_manager_fill.py` -> `58 passed`- `python -m pytest tests/unit/test_api_status.py tests/unit/test_playwright_guard.py tests/static/test_playwright_hygiene.py tests/unit/test_round12_rotate_sse_stream.py` -> `15 passed, 1 warning`- `python -m ruff check src` -> `All checks passed`- 变更文件 targeted ruff -> `All checks passed`- `docker compose config` -> 通过- `docker build -f Dockerfile.fast --build-arg GIT_SHA=0515-hardening --build-arg BUILD_TIME=2026-05-15T00:00:00Z -t autoteam:fast-0515 .` -> 通过- `docker run --rm autoteam:fast-0515 status` -> self-check `OK: 15 critical symbols imported`,self-check passed
已知非本轮阻塞:
- `python -m ruff check src tests` 仍失败于既有 `tests/unit/test_round12_wireup.py` 的 import-order、unused variable/import、`getattr` 常量属性问题。`src` 和本轮变更文件均已通过 ruff,本任务不顺手修改该无关 WIP。
## 结论
本轮与“加固、稳定、防止溢出、Docker 部署、默认不破坏 free 注册”直接相关的 `autoteam-1` 突出设计已全部吸收或被当前更强实现替代。剩余未吸收项不是本任务目标内的稳定性设计,或会降级当前 Round 11/12 主流程,已明确拒绝或记录为独立后续候选。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# 0515 Round 2:free 注册主流程批判性对比与加固计划
## 背景
用户要求在上一轮 Docker / runtime / Playwright 加固之后,再从批判性角度对比:
- 母板:`D:\Desktop\autoteam-1\AutoTeam`- 当前项目:`D:\Desktop\AutoTeam`
本轮目标是继续加固 free 帐号注册主流程,但不把“加固”理解为绕过平台风控、验证码、限制或批量滥用能力增强。可做范围限定为:
- 数据一致性- 状态一致性- 本地/远端席位边界- 幂等、早停、拒绝不安全任务- 失败分类和可审计性- 回归测试覆盖
## 主流程红线
以下路径不得被母板旧实现覆盖或削弱:
```textPOST /api/tasks/fill { leave_workspace: true } -> command = "fill-personal" -> cmd_fill(..., leave_workspace=True) -> _cmd_fill_personal() -> create_new_account(..., leave_workspace=True) -> create_account_direct(..., leave_workspace=True) -> _run_post_register_oauth(..., leave_workspace=True) -> remove_from_team(...) -> login_codex_via_browser(..., use_personal=True) -> plan_type == "free" -> STATUS_PERSONAL```
仍然禁止:
- 用母板旧 `manager.py` / `codex_auth.py` / `invite.py` 覆盖当前 Round 11/12 实现。- 让 `CHATGPT_API_TRANSPORT=auto` 泄漏到 free 注册、Personal OAuth、验证码或 workspace UI 选择;这些路径必须强制真实浏览器上下文。- 改变 Personal OAuth 的 5 次 retry、`plan_type=free` 接受条件、plan drift 失败记录。- 为“成功率”引入绕过验证码、人机验证、平台限制的逻辑。
## 批判性对比
| 维度 | 母板 `autoteam-1` | 当前 `AutoTeam` | 批判性结论 || --- | --- | --- | --- || free 注册主流程 | 母板主流程更短,直接注册后进入 Team OAuth / active 路径,缺少当前 personal/free 专门链路 | 当前已有 `leave_workspace=True`、踢出 Team、Personal OAuth、`plan_type=free`、`STATUS_PERSONAL`、plan drift 记录 | 当前主流程更强,不能回退到母板旧链路 || 身份 profile | 母板 `generate_signup_profile(today, rng)` 从生日推导年龄,并校验 `MIN_SIGNUP_AGE <= age <= MAX_SIGNUP_AGE` | 当前 `SignupProfile` 已作为同一 snapshot 贯穿注册和 OAuth,但 `birthday=random_birthday()` 与 `age=random_age()` 相互独立 | 当前已吸收“一份 profile 贯穿两阶段”,但还缺母板的“年龄/生日自洽” || Team 席位本地计数 | 母板 `_count_local_team_seat_accounts()` 明确统计 active/exhausted/auth_pending 等占席状态 | 当前 manager helper 已等价统计 `ACTIVE / EXHAUSTED / AUTH_INVALID`,但 API `post_fill` 的 fill-personal 轻量预检只数 `ACTIVE / EXHAUSTED` | 当前存在跨层不一致:API 入口可能漏数 `AUTH_INVALID`,导致本地已满时仍启动后台任务 || 注册失败阻断 | 母板有较清晰 `_classify_oauth_failure()` 和 timeout/no_valid_org recovery | 当前 Round 11/12 已把 Personal OAuth、workspace select、plan drift 和 terminal `RegisterBlocked` 分类做得更细 | 当前更强;本轮不回贴母板旧 OAuth 恢复逻辑 || 邮箱 provider | 母板有单体 `mail_provider.py` / `cloudflare_temp_email.py` | 当前有 `src/autoteam/mail/*`、fallback、probe、register dual path 和 provider chain history | 当前更强;不回贴旧 provider || CPA 同步 | 母板已有 CPA 同步 | 当前同步范围包含 active + personal,并有更多 token 删除守卫 | 当前更贴合 free/personal,不回退 || Docker/runtime | 母板已有快速镜像、runtime resources、Playwright lifecycle、transport、probe | 上一轮已吸收并测试 | 已完成,不在本轮重复 |
## Round 2 决策
### R2-1. 吸收母板 signup profile 的年龄/生日自洽
当前问题:
- `SignupProfile` 已经避免“注册页姓名/生日”和“OAuth about-you 姓名/生日”不一致。- 但 `birthday` 与 `age` 仍分别随机生成,可能出现生日推导年龄与 `age` 输入不一致。
实施:
- 保持当前 `SignupProfile` 字段形状不变:`full_name: str`、`birthday: dict[str, str]`、`age: str`。- 给 `generate_signup_profile()` 增加可选 `today` / `rng` 参数,兼容旧调用。- 从生日推导 `age`,并校验范围。- 保留当前 identity 姓名来源,不引入母板字段命名破坏。
验证:
- 新增/扩展 `tests/unit/test_round12_s3_cherry_pick.py`。- 检查生成的 `profile.age` 等于 `calculate_age(profile.birth_date, today)`。
### R2-2. API fill-personal 入口使用统一本地席位计数
当前问题:
- `manager._count_local_team_seat_accounts()` 认为 `STATUS_AUTH_INVALID` 也占 Team 席位。- `/api/tasks/fill` 入口只统计 `STATUS_ACTIVE / STATUS_EXHAUSTED`。- 这会造成 API 层和 manager 层对“是否本地已满”的判断不一致。
实施:
- `post_fill()` 的 `leave_workspace=True` 预检改用 `manager._count_local_team_seat_accounts(load_accounts())`。- 仍保持 409 fail-fast,不启动后台任务。- 不改变 `command = "fill-personal" if params.leave_workspace else "fill"`。
验证:
- 新增 API 单测:4 个本地 Team seat 中包含 `auth_invalid` 时,`post_fill(leave_workspace=True)` 返回 409 且不启动任务。- 保留现有 free 注册回归。
## 非目标
- 不改注册页面交互策略。- 不改 OAuth workspace selection 主逻辑。- 不改 `remove_from_team()` 语义。- 不改 `STATUS_PERSONAL` / `STATUS_AUTH_INVALID` 的状态含义。- 不增加绕过验证码、人机验证、平台风控或速率限制的能力。
## 验收命令
```bashpython -m pytest tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_free_registration_hardening.pypython -m pytest tests/unit/test_round11_personal_oauth_retry.py tests/unit/test_round11_session_token_injection.py tests/unit/test_round12_s4_register_dual_path.py tests/unit/test_manager_fill.pypython -m ruff check src/autoteam/signup_profile.py src/autoteam/api.py tests/unit/test_round12_s3_cherry_pick.py tests/unit/test_free_registration_hardening.py```
全量 `python -m ruff check src tests` 仍可能受既有 `tests/unit/test_round12_wireup.py` 未清理问题影响,本轮不把该无关 WIP 混入。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# 0515 实施计划:先加固外围,再保护主流程
## 当前阶段
状态:已实施并进入收尾审计。Phase 1-4 先按保守方式落地,第二轮已按母板把 Team API transport 默认值校正为 `auto`,并补齐 OAuth/UI 浏览器隔离。
## TODO
- [x] 创建 Trellis planning task:`.trellis/tasks/05-15-autoteam1-hardening-docker-apply`- [x] 建立 `prompts/0515` 文档目录- [x] 写入 PRD、SPEC、实施计划、调研记录- [x] 用户确认实施范围- [x] Phase 1:Docker/compose 加固- [x] Phase 2:runtime resources 与 Playwright lifecycle- [x] Phase 2.5:killable Playwright probe 吸收- [x] Phase 3:free 注册保护回归- [x] Phase 4:Team API transport 评估与母板对齐实施- [x] Phase 5:完整验证与收尾记录- [x] Phase 6:完成审计,确认 autoteam-1 优秀设计已吸收或被当前更强实现替代
## 推荐实施顺序
### Phase 1:Docker/compose 加固
变更范围:
- `docker-compose.yml`- `Dockerfile.fast`- `docs/docker.md`- `tests/integration/test_docker_guard.py`
工作内容:
- 给 compose 增加 `init: true`、`shm_size: "1gb"`、`mem_limit`、`memswap_limit`、`pids_limit`。- 增加资源阈值环境变量。- 增加 `/api/version` healthcheck。- 新增 `Dockerfile.fast`,但保留当前 Dockerfile 的版本指纹和 entrypoint self-check 约束。- 扩展 Docker guard 测试覆盖上述静态契约。
验证:
- `python -m pytest tests/integration/test_docker_guard.py`- `docker compose config`
### Phase 2:runtime resources 与 Playwright lifecycle
变更范围:
- `src/autoteam/runtime_resources.py`- `src/autoteam/playwright_lifecycle.py`- `src/autoteam/chatgpt_api.py`- `src/autoteam/api.py`- `tests/unit/test_runtime_resources.py`- `tests/unit/test_api_playwright_cleanup.py`
工作内容:
- 新增资源探针,支持 cgroup memory/pids 和 browser zombie 统计。- 在低风险 API status 或自动巡检日志中接入资源快照。- 新增统一 Playwright close helper。- 修改 `ChatGPTTeamAPI._launch_browser()` 和 `stop()` 以保证失败清理和幂等释放。- 对 API 中创建 `ChatGPTTeamAPI` 的失败路径补清理。
验证:
- `python -m pytest tests/unit/test_runtime_resources.py`- `python -m pytest tests/unit/test_api_playwright_cleanup.py`- `python -m pytest tests/unit/test_playwright_guard.py tests/static/test_playwright_hygiene.py`
### Phase 3:free 注册保护回归
变更范围:
- 原则上不改 free 注册代码,只跑并补充保护测试。
验证:
- `python -m pytest tests/unit/test_round11_personal_oauth_retry.py`- `python -m pytest tests/unit/test_round11_session_token_injection.py`- `python -m pytest tests/unit/test_round12_s4_register_dual_path.py`- `python -m pytest tests/unit/test_manager_fill.py`- 如 Phase 2 触碰 API task 调度,再补跑 `tests/unit/test_round12_rotate_sse_stream.py`
### Phase 4:Team API transport 评估
已在 Phase 1-3 稳定后实施,并在第二轮对照母板后改为默认 `auto`:
- 新增 `curl-cffi` 依赖和 `chatgpt_transport.py`- 默认对齐 `autoteam-1` 为 `auto`- 仅用于非注册、非 OAuth、非 workspace UI 的 backend API fetch- HTML challenge / token miss / 403 / 401 自动回退 Playwright- `SessionCodexAuthFlow` 等 OAuth/UI 路径显式 `require_browser=True`
验证:
- 新增 transport 单测- 确认 free 注册保护测试仍通过
### Phase 6:吸收审计
工作内容:
- 建立 `autoteam-1` 设计点到当前 artifact 的 checklist。- 对每个显式需求和源端突出设计标记:已吸收 / 当前更强实现替代 / 明确拒绝。- 用文件、测试、Docker 运行结果和 lint 结果作为证据,不能只用意图或清单。
## 推荐选项
实际执行结果:Phase 1-3 先完成,之后补做 Phase 4;第二轮 codex review 后以 `D:\Desktop\autoteam-1\AutoTeam` 为规范,将默认值校正为 `auto`。
- Docker 和资源清理收益高,风险低,已完成。- free 注册主流程未主动改动,已通过回归保护。- `curl_cffi` transport 已按母板默认 `auto` 落地,并通过 `require_browser=True` 与生命周期清理保护真实浏览器路径。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122# 0515 PRD:吸收 autoteam-1 加固能力并保护 free 注册主流程
## 背景
用户要求以 `D:\Desktop\autoteam-1` 为基础,将其中“扬长避短”的能力应用到当前 `D:\Desktop\AutoTeam`:重点是加固、稳定、防止溢出、Docker 部署,同时明确要求不要破坏 free 帐号注册的主流程。本文件是实施前的权威需求文档;在本文件和 `spec.md`、`implementation-plan.md` 决定之前,不修改业务代码。
## 当前事实
- 当前项目路径:`D:\Desktop\AutoTeam`,Trellis task:`.trellis/tasks/05-15-autoteam1-hardening-docker-apply`。- 当前项目已有 Docker 基础:`Dockerfile`、`docker-compose.yml`、`docker-entrypoint.sh`、`tests/integration/test_docker_guard.py`。- 当前项目已有 free 注册主流程:`POST /api/tasks/fill { leave_workspace: true }` -> `cmd_fill(..., leave_workspace=True)` -> `_run_post_register_oauth(..., leave_workspace=True)` -> Personal OAuth -> `plan_type=free` 校验和 plan drift 记录。- 当前项目已有比 `autoteam-1` 更新的 Round 11/12 保护:`master_health`、`oauth_workspace`、`workspace_pool`、`quota_predictor`、`mail/register_dual_path.py`、多 provider 回退、Personal OAuth 重试和大量单测。- `D:\Desktop\autoteam-1\AutoTeam` 不是应整包覆盖的目标;它更适合作为局部能力来源。- 记忆中 `D:\Desktop\autoteam-1\codex-watchdog` 的经验提示:自动化加固必须默认保守,不得误打扰活跃 Codex/注册会话;dry-run 和“不注入/不破坏”证据优先。
## 目标
在不破坏 free 帐号注册主流程的前提下,将 `autoteam-1` 中对当前项目有正向收益的稳定性和部署能力按阶段吸收进来,使当前项目具备更可靠的 Docker 运行边界、资源观测、Playwright 生命周期清理和溢出防护。
## 非目标
- 不重写 free 注册流程。- 不直接用 `autoteam-1` 的旧 `manager.py` / `codex_auth.py` / `invite.py` 覆盖当前实现。- 不允许 HTTP transport 改变 OAuth、注册、workspace 选择结果;默认 transport 对齐母板为 `auto`,但浏览器依赖路径必须显式强制 Playwright 且可回退。- 不在未验证前宣称 Docker 镜像可生产部署。- 不清理与本任务无关的 dirty worktree 文件。
## 需求
### R1. 迁移前对照矩阵
必须先形成“吸收 / 改写 / 拒绝”的矩阵,逐项说明来源文件、目标文件、收益、风险和验证方式。
首批候选:
- 吸收:`runtime_resources.py` -> 当前项目新增轻量资源探针。- 吸收并适配:`playwright_lifecycle.py` -> 当前 `ChatGPTTeamAPI`、API 登录/探测路径的 best-effort cleanup。- 吸收并增强:`Dockerfile.fast` -> 当前项目增量构建文件,但保留 build args、OCI label、entrypoint self-check。- 吸收:compose `init: true`、`shm_size`、内存/PID 边界和资源告警环境变量。- 按母板吸收:`chatgpt_transport.py` / `curl_cffi`,默认 `auto` 仅用于 Team backend API,不能进入 free 注册 / Personal OAuth / workspace UI 选择路径。- 吸收:`playwright_probe.py`,将后台 Team 人数探测隔离到可超时杀进程组的短生命周期子进程。- 拒绝:旧 free/direct register 主流程覆盖当前 Round 11/12 实现。
### R2. Docker 部署加固
`docker-compose.yml` 应具备以下能力:
- 启用 `init: true`。- 为 Chromium/Playwright 设置共享内存边界,如 `shm_size: "1gb"`。- 设置内存和 PID 上限,防止浏览器或任务异常增长拖垮宿主机。- 设置 `AUTOTEAM_MEMORY_WARN_RATIO`、`AUTOTEAM_ZOMBIE_WARN_THRESHOLD` 等运行时资源告警变量。- 增加 `healthcheck`,优先检查 `http://127.0.0.1:8787/api/version`。- 保留现有 build args:`GIT_SHA`、`BUILD_TIME`。
### R3. 运行时资源与溢出防护
新增或吸收轻量资源探针:
- 读取 `/proc/self/status`、cgroup memory、cgroup pids。- 统计 Chromium/Playwright live/zombie 进程。- 内存使用比例超过阈值时记录 warning 并执行 `gc.collect()`。- browser zombie 超阈值时记录 warning,提示 `init` / reaper 配置。- 资源快照应被 API status 或自动巡检日志可见,但不得阻塞主流程。
### R4. Playwright 生命周期清理
所有新接入清理逻辑必须是 best-effort:
- 关闭顺序固定为 page -> context -> browser -> playwright。- `_launch_browser()` 失败时必须调用 `stop()` 清理半初始化对象。- `stop()` 必须幂等,可重复调用。- API 登录、Team 成员探测、manual account、main codex 等路径若创建 `ChatGPTTeamAPI` 后失败,必须释放对象。- 不能把 Playwright 清理异常向上传播为业务失败,除非原始业务操作已经失败。
### R5. free 注册主流程保护
以下行为必须保持兼容:
- Web/API 请求 `POST /api/tasks/fill` 的 `leave_workspace=True` 语义不变。- `cmd_fill(..., leave_workspace=True)` 仍走当前注册、kick、Personal OAuth、plan drift 记录路径。- `_run_post_register_oauth(..., leave_workspace=True)` 的 5 次 Personal OAuth retry、`plan_type=free` 校验、失败记录和状态落盘不被削弱。- 不改 `STATUS_PERSONAL` / `STATUS_STANDBY` / `STATUS_AUTH_INVALID` 等状态语义。- 不改 `register_failures.json` 的关键分类语义。- 不让 Docker/runtime/transport 默认改变注册浏览器上下文、workspace select 或 OAuth callback 逻辑。
### R6. 验证证据
实施后至少需要以下验证:
- `python -m pytest tests/integration/test_docker_guard.py`- `python -m pytest tests/unit/test_runtime_resources.py`(新增后)- `python -m pytest tests/unit/test_api_playwright_cleanup.py`(新增或适配后)- free 注册保护回归: - `python -m pytest tests/unit/test_round11_personal_oauth_retry.py` - `python -m pytest tests/unit/test_round11_session_token_injection.py` - `python -m pytest tests/unit/test_round12_s4_register_dual_path.py` - `python -m pytest tests/unit/test_manager_fill.py`- `ruff check` 或 `python -m ruff check src tests`(以项目当前工具为准)- `docker compose config`- Docker 可用时再执行 `docker compose build` 或最小镜像构建验证。
## 验收标准
- `prompts/0515/prd.md`、`prompts/0515/spec.md`、`prompts/0515/implementation-plan.md` 完整存在并可审阅。- 代码实施前有明确的迁移矩阵和阶段计划。- 实施完成后,Docker 配置具备 init、shared memory、资源边界、healthcheck 和 build args。- 资源探针在非 Linux / 无 cgroup 环境中优雅降级,不抛异常。- Playwright lifecycle 清理新增测试通过。- free 注册相关回归测试通过,且没有默认启用影响 free 注册主流程的新 transport。- 变更说明中明确列出未吸收项和原因。
## 决策
采用“安全分层吸收”方案:
1. 先吸收 Docker/运行时资源/Playwright 清理这些低耦合能力。2. `curl_cffi` transport 按母板默认 `auto` 吸收;失败、HTML challenge 或鉴权异常必须回退 Playwright,OAuth/UI/free 注册路径必须显式强制浏览器上下文。3. free 注册链路只加保护性回归测试,不主动重构。
## 外部调研
详见 `research-docker-playwright-hardening.md`。12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# 0515 调研记录:Docker 与 Playwright 稳定性加固
## 调研目标
本次任务不是从 `D:\Desktop\autoteam-1` 整包迁移,而是在当前 `D:\Desktop\AutoTeam` 的主流程基础上,吸收对稳定性、资源边界、Docker 部署和浏览器生命周期更有价值的部分。
## 外部资料
- Docker Compose services reference: <https://docs.docker.com/reference/compose-file/services/>- Docker Compose deploy resources reference: <https://docs.docker.com/reference/compose-file/deploy/#resources>- Playwright Python Docker guide: <https://playwright.dev/python/docs/docker>- Playwright Docker guide: <https://playwright.dev/docs/docker>
## 可采纳结论
- `init: true` 适合作为容器内 PID 1 兜底,用于信号转发和僵尸进程回收。当前服务长期运行、会启动 Chromium/Playwright 子进程,适合启用。- Chromium 在 Docker 默认 `/dev/shm` 较小的环境下容易不稳定。Playwright 官方建议 `--ipc=host`;对单机 compose 更保守的做法是先设置 `shm_size: "1gb"`,保持隔离同时提升 Chromium 稳定性。- `healthcheck` 应检查真实 API 可用性,而不是只检查进程存在。当前项目已有 `/api/version` 免鉴权端点,可作为低风险健康检查目标。- 资源限制应避免“无限增长”:内存、PID 和浏览器子进程数量需要边界。compose 可使用 `mem_limit` / `pids_limit` 等直接服务字段,也可在兼容场景下补充 `deploy.resources`。- Playwright 官方镜像包含浏览器和系统依赖;当前项目已有自建 `python:3.12-slim + playwright install-deps chromium` 路径,可以先保留,只新增 `Dockerfile.fast` 作为增量构建辅助,不替换默认稳定构建。
## 本地代码对照
当前 `D:\Desktop\AutoTeam` 已有:
- `Dockerfile`:已有 `GIT_SHA` / `BUILD_TIME` build args、OCI label、`/api/version` 对应环境变量。- `docker-entrypoint.sh`:已有关键 import self-check,失败会 `exit 1` 触发 crash-loop。- `tests/integration/test_docker_guard.py`:已有 Dockerfile、compose build args、entrypoint self-check、ruff F821 守卫。- `src/autoteam/_playwright_guard.py` 与 `api.py:_PlaywrightExecutor`:已有 sync Playwright 专用线程和 asyncio loop 防护。- free 注册相关链路已经比 `autoteam-1` 更新,包含 `leave_workspace=True`、`_run_post_register_oauth`、Personal OAuth 重试、plan drift 记录、workspace pool、注册双路径和一批 Round 11/12 测试。
`D:\Desktop\autoteam-1\AutoTeam` 可吸收:
- `docker-compose.yml` 中的 `init: true`、`shm_size: "1gb"`、`mem_limit`、`memswap_limit`、`pids_limit`、`AUTOTEAM_MEMORY_WARN_RATIO`、`AUTOTEAM_ZOMBIE_WARN_THRESHOLD`。- `Dockerfile.fast` 的增量构建思路,但必须补齐当前项目已有的 build args、OCI label 和 self-check 约束。- `src/autoteam/runtime_resources.py` 的 cgroup memory / pids / browser zombie 轻量探针。- `src/autoteam/playwright_lifecycle.py` 的统一关闭顺序。- `src/autoteam/chatgpt_transport.py` 的 `curl_cffi` HTTP transport 思路;按母板默认 `auto` 用于 Team backend API,但不能改变 free 注册和浏览器 OAuth 行为。- `src/autoteam/playwright_probe.py` 的短生命周期 Playwright 探针,用于把后台人数探测隔离到可超时 kill 的子进程。
## curl_cffi 参考
Context7 查询达到额度限制,本轮回退到官方文档。`curl_cffi` 官方文档说明 `Session` 会复用 cookies/连接,并支持 `impersonate`、`proxies`、`timeout`、`allow_redirects` 等参数;这与本次 HTTP transport 的实现点一致。经第二轮对照母板,当前项目默认值调整为 `CHATGPT_API_TRANSPORT=auto`,但官方能力不等于能稳定绕过 ChatGPT/Cloudflare challenge,遇到 HTML/challenge/401 等情况必须回退浏览器。
参考:<https://curl-cffi.readthedocs.io/en/stable/index.html>、<https://curl-cffi.readthedocs.io/en/stable/_modules/curl_cffi/requests/session.html>
## 约束
- 不直接覆盖当前 `src/autoteam/manager.py`、`codex_auth.py`、`oauth_workspace.py`、`mail/register_dual_path.py`。- 不把 `autoteam-1` 的旧注册实现回贴到当前项目,因为当前项目已有更晚的 Round 11/12 修复。- `curl_cffi` 已按母板默认 `auto` 引入;不得替代 free 注册、Personal OAuth、验证码或 workspace UI 的真实浏览器路径,避免改变主流程行为证据。- 所有 Docker 改动必须有静态测试和 `docker compose config` 验证;真正构建镜像前需要先确认本地 Docker 可用。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142# 0515 SPEC:autoteam-1 能力吸收与 free 注册保护契约
## 1. 总体契约
本任务只允许做“选择性吸收”。所有代码实现必须以当前 `D:\Desktop\AutoTeam` 为基线,以 `D:\Desktop\autoteam-1` 为参考来源。若两者冲突,除非 PRD 明确要求,否则当前项目的 Round 11/12 注册链路优先。
## 2. 文件级迁移规则
### 2.1 允许直接新增或改写的低耦合文件
- `src/autoteam/runtime_resources.py`- `src/autoteam/playwright_lifecycle.py`- `src/autoteam/playwright_probe.py`- `src/autoteam/chatgpt_transport.py`- `tests/unit/test_runtime_resources.py`- `tests/unit/test_api_playwright_cleanup.py`- `tests/unit/test_chatgpt_transport.py`- `Dockerfile.fast`- `docker-compose.yml`- `docs/docker.md`- `tests/integration/test_docker_guard.py`- `pyproject.toml` 仅在新增依赖或测试配置确有必要时修改
### 2.2 只允许定点修改的高风险文件
- `src/autoteam/api.py` - 只允许增加资源快照字段、Playwright cleanup 调用、executor stop 钩子、health/status 辅助。 - 不允许改变 `/api/tasks/fill` 的 `leave_workspace` 入参和任务调度语义。- `src/autoteam/chatgpt_api.py` - 只允许增加 `_launch_browser()` 失败清理、`stop()` 幂等清理、Team API transport 的封装入口。 - transport 默认值按母板为 `auto`;不允许改变 free 注册、Personal OAuth、验证码、workspace UI 的浏览器路径。- `src/autoteam/config.py` - 只允许新增运行时资源阈值配置、HTTP transport 配置。 - 新配置必须有安全默认值。
### 2.3 禁止覆盖的文件和区域
- `src/autoteam/manager.py` 中 `_run_post_register_oauth` 的 Personal/free 主体逻辑不得被旧实现覆盖。- `src/autoteam/codex_auth.py` 的 Personal OAuth、workspace select、plan_type 校验不得被旧实现覆盖。- `src/autoteam/oauth_workspace.py`、`src/autoteam/workspace_pool.py`、`src/autoteam/mail/register_dual_path.py` 不得为迁移旧功能而降级。- 不得删除 Round 11/12 相关单测。
## 3. Docker 契约
`docker-compose.yml` 必须满足:
- `services.autoteam.init: true`- `services.autoteam.shm_size` 不小于 `1gb`- 设置 PID 边界,推荐 `pids_limit: 768`- 设置内存边界,推荐 `mem_limit: "2g"`;如果同时使用 `deploy.resources`,必须避免与直接字段语义冲突。- 保留当前 `build.args.GIT_SHA` 与 `build.args.BUILD_TIME`。- 添加健康检查: - `test` 使用 `curl -fsS http://127.0.0.1:8787/api/version` - 设置合理 `interval`、`timeout`、`retries`、`start_period`- 允许容器访问宿主代理的说明写入 `docs/docker.md`,但不默认强制 `network_mode: host`。
`Dockerfile.fast` 若新增,必须满足:
- 继承当前稳定镜像时不得绕开 entrypoint self-check。- 支持 `GIT_SHA` / `BUILD_TIME` 或明确继承基础镜像中的版本指纹。- 必须复制 `docker-entrypoint.sh` 并做 CRLF 处理。- 必须在文档中标明用途:仅用于本地快速迭代,不替代首次完整构建。
## 4. runtime resources 契约
`runtime_resources.py` 必须满足:
- 不依赖 psutil。- 所有 `/proc`、`/sys/fs/cgroup` 读取必须捕获 `OSError` / `ValueError` 并返回 `None` 或空统计。- `collect_runtime_resource_snapshot()` 不抛异常,返回 dict 至少包含: - `rss_mb` - `cgroup_memory_mb` - `cgroup_memory_limit_mb` - `cgroup_memory_usage_ratio` - `pids_current` - `pids_max` - `browser_process_total` - `browser_process_live` - `browser_process_zombie`- `log_runtime_resource_snapshot(logger, label=...)` 可执行 `gc.collect()`,但不得中断业务流程。- 阈值从环境变量读取: - `AUTOTEAM_MEMORY_WARN_RATIO` 默认 `0.85` - `AUTOTEAM_ZOMBIE_WARN_THRESHOLD` 默认 `20`
## 5. Playwright lifecycle 契约
`playwright_lifecycle.py` 必须满足:
- `close_playwright_objects(page, context, browser, playwright, logger=None, label="playwright")`- 关闭顺序固定:page -> context -> browser -> playwright.stop。- 任一 close/stop 抛错时只记录 debug,不继续向外抛。- `ChatGPTTeamAPI.stop()` 必须在释放后清空对象字段。- `ChatGPTTeamAPI._launch_browser()` 在半初始化失败时必须调用 `stop()` 再重新抛原异常。
## 6. transport 契约
`curl_cffi` transport 按 `D:\Desktop\autoteam-1\AutoTeam` 作为默认 Team API 优化吸收:
- 默认值对齐母板为 `CHATGPT_API_TRANSPORT=auto`。- 只允许用于无需真实浏览器上下文的 ChatGPT backend API 读写。- 遇到 HTML challenge、403、401 token missing、结构异常时必须回退浏览器路径。- 不允许用于 free 注册、Personal OAuth、验证码、workspace UI 选择;这些路径必须显式 `require_browser=True` 或自建 Playwright context。- 依赖 `curl-cffi` 必须进入 `pyproject.toml` / `uv.lock`,保证 Docker 内默认 `auto` 后真实可用。
## 6.1 Playwright probe 契约
短生��周期探针用于后台稳定性加固:
- `python -m autoteam.playwright_probe team-member-count` 只输出 JSON。- 父进程 helper 必须设置超时,超时后 best-effort kill 整个进程组。- 探针失败时自动巡检只能视为 unknown,不得让主 API 线程崩溃。- 该探针只能用于后台校验,不得替代 free 注册 / OAuth 的浏览器上下文。
## 7. free 注册保护契约
实施时必须维护以下红线:
- 不改变 `FillParams.leave_workspace` 默认值和含义。- 不改变 `command = "fill-personal" if params.leave_workspace else "fill"`。- 不改变 `_run_post_register_oauth(..., leave_workspace=True)` 的 5 次 retry 和 `plan_type=free` 接受条件。- 不改变 plan drift 记录、`record_failure` 分类、Personal quota probe 和状态落盘。- 不改变 `auths/*-free*.json` 与 Team auth 文件互斥清理策略。
任何触碰上述区域,必须先更新本 PRD/spec,并单独列出兼容性证明。
## 8. 测试契约
每个实施阶段必须带测试:
- Docker 配置:扩展 `tests/integration/test_docker_guard.py`- 资源探针:新增 `tests/unit/test_runtime_resources.py`- Playwright 清理:新增或移植 `tests/unit/test_api_playwright_cleanup.py`- HTTP transport:新增 `tests/unit/test_chatgpt_transport.py`- free 注册保护:运行现有 Round 11/12 相关单测- 静态质量:ruff F401/F811/F821 继续通过
## 9. 回滚契约
- Docker/compose 回滚必须不影响本地非 Docker 启动。- runtime resources 集成失败时,可以保留模块但禁用调用点。- Playwright cleanup 若导致路径差异,优先回滚调用点而不是删除工具模块。- transport 若引入,必须可通过环境变量一键回退到 Playwright 路径。3 unmodified lines4567893 unmodified linesdescription = "ChatGPT Team 账号自动轮转管理工具"requires-python = ">=3.10"dependencies = ["fastapi>=0.135.3","playwright>=1.40.0","requests>=2.28.0",3 unmodified lines456789103 unmodified linesdescription = "ChatGPT Team 账号自动轮转管理工具"requires-python = ">=3.10"dependencies = ["curl-cffi>=0.13.0","fastapi>=0.135.3","playwright>=1.40.0","requests>=2.28.0",
2 unmodified lines3456788 unmodified lines17181920212249 unmodified lines7273747576771129 unmodified lines12071208120912101211121212131214846 unmodified lines20612062206320642065206620672068184 unmodified lines225322542255225622572258177 unmodified lines2436243724382439244024412442244324 unmodified lines246824692470247124722473247429 unmodified lines25042505250625072508250925102511151 unmodified lines266326642665266626672668266926702671267226732674241 unmodified lines29162917291829192920292116 unmodified lines29382939294029412942294361 unmodified lines3005300630073008300930102 unmodified linesimport jsonimport loggingimport osimport threadingimport timeimport uuid8 unmodified linesfrom pydantic import BaseModel, Field, field_validatorfrom autoteam.config import API_KEYfrom autoteam.textio import read_textlogger = logging.getLogger(__name__)49 unmodified linesfinally:logger.info("[lifespan] stopping")_auto_check_stop.set()app = FastAPI(1129 unmodified linesdef _do_start(email):api = ChatGPTTeamAPI()result = api.begin_admin_login(email)return api, resultapi, result = _pw_executor.run(_do_start, params.email.strip())step = result["step"]846 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()chatgpt.start()try:return remove_from_team(chatgpt, email)finally:chatgpt.stop()184 unmodified lines"accounts": sanitized_accounts,"summary": summary,"quota_cache": quota_cache,}177 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()chatgpt.start()try:members, invites = fetch_team_state(chatgpt)local_emails = {a["email"].lower() for a in load_accounts()}24 unmodified linesfinally:chatgpt.stop()return _pw_executor.run(_fetch_team_members)finally:_playwright_lock.release()29 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()chatgpt.start()try:if member_type == "invite":path = f"/backend-api/accounts/{account_id}/invites/{user_id}"action_text = "取消邀请"151 unmodified lines则直接返回 409,不启动后台任务(队列化拒绝,Solution C)。本地状态足够用,无需启动Playwright 远程查询,避免给前端按错按钮带来额外开销。"""from autoteam.manager import TEAM_SUB_ACCOUNT_HARD_CAP, cmd_fillif params.leave_workspace:from autoteam.accounts import STATUS_ACTIVE, STATUS_EXHAUSTED, load_accountsin_team_local = sum(1 for a in load_accounts() if a.get("status") in (STATUS_ACTIVE, STATUS_EXHAUSTED))if in_team_local >= TEAM_SUB_ACCOUNT_HARD_CAP:raise HTTPException(status_code=409,241 unmodified lines_AUTO_FILL_COOLDOWN_SECONDS = 1800 # 30 mindef _auto_check_loop():"""后台巡检线程:定期检查额度,多个账号低于阈值时自动轮转"""from autoteam.accounts import STATUS_ACTIVE, load_accounts16 unmodified linestry:cfg = _auto_check_config # 重新读取accounts = load_accounts()active = [a61 unmodified linesif backoff_triggered:continueif not _playwright_lock.acquire(blocking=False):logger.info("[巡检] active=%d < %d 但有任务在跑,本轮先跳过自动补位",2 unmodified lines345678910118 unmodified lines2021222324252649 unmodified lines767778798081828384851129 unmodified lines121512161217121812191220122112221223122412251226846 unmodified lines20732074207520762077207820792080184 unmodified lines2265226622672268226922702271177 unmodified lines2449245024512452245324542455245624 unmodified lines24812482248324842485248624872488248924902491249229 unmodified lines25222523252425252526252725282529151 unmodified lines268126822683268426852686268726882689269026912692241 unmodified lines29342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303816 unmodified lines305530563057305830593060306161 unmodified lines31233124312531263127312831293130313131323133313431353136313731382 unmodified linesimport jsonimport loggingimport osimport signalimport subprocessimport sysimport threadingimport timeimport uuid8 unmodified linesfrom pydantic import BaseModel, Field, field_validatorfrom autoteam.config import API_KEYfrom autoteam.runtime_resources import collect_runtime_resource_snapshot, log_runtime_resource_snapshotfrom autoteam.textio import read_textlogger = logging.getLogger(__name__)49 unmodified linesfinally:logger.info("[lifespan] stopping")_auto_check_stop.set()try:_pw_executor.stop()except Exception as exc:logger.warning("[lifespan] stopping Playwright executor failed: %s", exc)app = FastAPI(1129 unmodified linesdef _do_start(email):api = ChatGPTTeamAPI()try:result = api.begin_admin_login(email)return api, resultexcept Exception:api.stop()raiseapi, result = _pw_executor.run(_do_start, params.email.strip())step = result["step"]846 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()try:chatgpt.start()return remove_from_team(chatgpt, email)finally:chatgpt.stop()184 unmodified lines"accounts": sanitized_accounts,"summary": summary,"quota_cache": quota_cache,"runtime_resources": collect_runtime_resource_snapshot(),}177 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()try:chatgpt.start()members, invites = fetch_team_state(chatgpt)local_emails = {a["email"].lower() for a in load_accounts()}24 unmodified linesfinally:chatgpt.stop()try:return _pw_executor.run(_fetch_team_members)except HTTPException:raiseexcept Exception as exc:raise HTTPException(status_code=502, detail=str(exc)) from excfinally:_playwright_lock.release()29 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()try:chatgpt.start()if member_type == "invite":path = f"/backend-api/accounts/{account_id}/invites/{user_id}"action_text = "取消邀请"151 unmodified lines则直接返回 409,不启动后台任务(队列化拒绝,Solution C)。本地状态足够用,无需启动Playwright 远程查询,避免给前端按错按钮带来额外开销。"""from autoteam.manager import TEAM_SUB_ACCOUNT_HARD_CAP, _count_local_team_seat_accounts, cmd_fillif params.leave_workspace:from autoteam.accounts import load_accountsin_team_local = _count_local_team_seat_accounts(load_accounts())if in_team_local >= TEAM_SUB_ACCOUNT_HARD_CAP:raise HTTPException(status_code=409,241 unmodified lines_AUTO_FILL_COOLDOWN_SECONDS = 1800 # 30 mindef _playwright_probe_command(*args: str) -> list[str]:return [sys.executable, "-m", "autoteam.playwright_probe", *args]def _kill_subprocess_group(proc: subprocess.Popen) -> None:try:if os.name == "nt":subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],capture_output=True,text=True,check=False,)else:os.killpg(proc.pid, signal.SIGKILL)except Exception:try:proc.kill()except Exception:passdef _parse_playwright_probe_stdout(stdout: str) -> dict:text = (stdout or "").strip()if not text:return {}lines = [line.strip() for line in text.splitlines() if line.strip()]for line in reversed(lines):if not line.startswith(("{", "[")):continuetry:parsed = json.loads(line)except json.JSONDecodeError:continuereturn parsed if isinstance(parsed, dict) else {"result": parsed}parsed = json.loads(text)return parsed if isinstance(parsed, dict) else {"result": parsed}def _run_playwright_probe(*args: str, timeout_seconds: float = 30) -> dict:cmd = _playwright_probe_command(*args)env = os.environ.copy()env["AUTOTEAM_PROBE_MODE"] = "1"proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,env=env,start_new_session=True,)try:stdout, stderr = proc.communicate(timeout=max(1.0, float(timeout_seconds)))except subprocess.TimeoutExpired as exc:_kill_subprocess_group(proc)try:proc.communicate(timeout=1)except Exception:passraise TimeoutError(f"Playwright probe timeout: {' '.join(args)}") from excstdout = (stdout or "").strip()stderr = (stderr or "").strip()if proc.returncode != 0:detail = stderr or stdout or f"exit={proc.returncode}"raise RuntimeError(detail)return _parse_playwright_probe_stdout(stdout) if stdout else {}def _auto_check_team_member_count(timeout_seconds: float = 30, retries: int = 2) -> int:"""Return Team member count via a killable subprocess probe; -1 means unknown."""for attempt in range(1, max(1, retries) + 1):try:result = _run_playwright_probe("team-member-count", timeout_seconds=timeout_seconds)except TimeoutError:if attempt < retries:logger.warning("[巡检] Team 人数探针超时(>%ss),准备重试第 %d/%d 次",timeout_seconds,attempt + 1,retries,)continuelogger.warning("[巡检] Team 人数探针超时(>%ss,已重试 %d 次),本轮视为未知", timeout_seconds, retries)return -1except Exception as exc:logger.warning("[巡检] Team 人数探针失败: %s", exc)return -1try:return int(result.get("count", -1))except Exception:return -1def _auto_check_loop():"""后台巡检线程:定期检查额度,多个账号低于阈值时自动轮转"""from autoteam.accounts import STATUS_ACTIVE, load_accounts16 unmodified linestry:cfg = _auto_check_config # 重新读取log_runtime_resource_snapshot(logger, label="auto-check")accounts = load_accounts()active = [a61 unmodified linesif backoff_triggered:continueactual_team_count = _auto_check_team_member_count(timeout_seconds=30, retries=2)if actual_team_count >= TEAM_SUB_ACCOUNT_HARD_CAP + 1:logger.info("[巡检] 本地 active=%d < %d,但 Team 实际成员数=%d 已满;先跳过 auto-fill,等待同步/对账稳定",len(active),TEAM_SUB_ACCOUNT_HARD_CAP,actual_team_count,)continueif not _playwright_lock.acquire(blocking=False):logger.info("[巡检] active=%d < %d 但有任务在跑,本轮先跳过自动补位",
17 unmodified lines1819202122232469 unmodified lines94959697989915 unmodified lines1151161171181191201211221231241251261271038 unmodified lines1166116711681169117011711172117311741175117611771178117911803 unmodified lines11841185118611871188118984 unmodified lines1274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113128 unmodified lines13211322132313241325132613271328254 unmodified lines158315841585158615871588158915901591159215931594159515961597159817 unmodified linesget_chatgpt_workspace_name,update_admin_state,)from autoteam.config import get_playwright_launch_optionsfrom autoteam.textio import read_textlogger = logging.getLogger(__name__)69 unmodified linesself.login_email = Noneself.login_password = Noneself.workspace_options_cache = []def _visible_locator_in_frames(self, selectors, timeout_ms=5000):selector = ", ".join(selectors)15 unmodified linesdef _launch_browser(self):SCREENSHOT_DIR.mkdir(exist_ok=True)self.playwright = sync_playwright().start()self.browser = self.playwright.chromium.launch(**get_playwright_launch_options())self.context = self.browser.new_context(viewport={"width": 1280, "height": 800},user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",)self.page = self.context.new_page()def _log_login_state(self, label):try:1038 unmodified linesself.workspace_name = get_chatgpt_workspace_name()self.start_with_session(session_token, self.account_id, self.workspace_name)def start_with_session(self, session_token, account_id, workspace_name=""):"""用指定的 session/account 启动浏览器上下文。"""if not session_token:raise FileNotFoundError("缺少会话信息")self.account_id = account_id or ""self.workspace_name = workspace_name or ""if not self.account_id:raise RuntimeError("缺少 workspace/account ID")self._launch_browser()logger.info("[ChatGPT] 访问 chatgpt.com 过 Cloudflare...")self.page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=60000)3 unmodified linesself._fetch_access_token()self._auto_detect_workspace()def _auto_detect_workspace(self):if self.workspace_name:return self.workspace_name84 unmodified lineslogger.warning("[ChatGPT] 未能获取 access token,将尝试无 token 调用")return Nonedef _api_fetch(self, method, path, body=None):raw_headers = {"Content-Type": "application/json","chatgpt-account-id": self.account_id,"oai-device-id": self.oai_device_id,"oai-language": "en-US",}if self.access_token:raw_headers["authorization"] = f"Bearer {self.access_token}"# Round 11 patch — fetch RequestInit headers 必须 ISO-8859-1 (Latin1)。# 任何 None / bytes / 含 unicode 的 value 都 sanitize,避免 Browser fetch 抛# "String contains non ISO-8859-1 code point"。# 见 prompts/issues1.md / Round 11 task PRD。headers_js = {}for k, v in raw_headers.items():if v is None:# null header value 直接 skip(避免传 "None" 字符串到 fetch)continueif isinstance(v, bytes):v = v.decode("ascii", errors="replace")else:v = str(v)sanitized = v.encode("latin-1", errors="replace").decode("latin-1")if sanitized != v:logger.warning("[ChatGPT] _api_fetch header %s 含非 ISO-8859-1 字符已被替换: %r -> %r",k,v[:60],sanitized[:60],)headers_js[k] = sanitizedjs_code = """async ([method, url, headers, body]) => {try {const opts = { method, headers };8 unmodified linesreturn self.page.evaluate(js_code,[method, f"https://chatgpt.com{path}", headers_js, json.dumps(body) if body else None],)# POST /invites 失败时的重试间隔(秒)。rate_limited / network 类错误按此序列退避。_INVITE_POST_RETRY_DELAYS = (5, 15)254 unmodified linesdef stop(self):try:if self.browser:self.browser.close()except Exception:passtry:if self.playwright:self.playwright.stop()except Exception:passself.browser = Noneself.context = Noneself.page = Noneself.playwright = None17 unmodified lines18192021222324252669 unmodified lines9697989910010110210315 unmodified lines1191201211221231241251261271281291301311321331341351361371381038 unmodified lines11771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712583 unmodified lines126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136484 unmodified lines1449145014511452145314541455145614578 unmodified lines146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522254 unmodified lines17771778177917801781178217831784178517861787178817891790179117921793179417951796179717 unmodified linesget_chatgpt_workspace_name,update_admin_state,)from autoteam.chatgpt_transport import build_chatgpt_transportfrom autoteam.config import get_playwright_launch_optionsfrom autoteam.playwright_lifecycle import close_playwright_objectsfrom autoteam.textio import read_textlogger = logging.getLogger(__name__)69 unmodified linesself.login_email = Noneself.login_password = Noneself.workspace_options_cache = []self.http_transport = Noneself.transport_name = Nonedef _visible_locator_in_frames(self, selectors, timeout_ms=5000):selector = ", ".join(selectors)15 unmodified linesdef _launch_browser(self):SCREENSHOT_DIR.mkdir(exist_ok=True)if self.playwright or self.browser or self.context or self.page:self.stop()try:self.playwright = sync_playwright().start()self.browser = self.playwright.chromium.launch(**get_playwright_launch_options())self.context = self.browser.new_context(viewport={"width": 1280, "height": 800},user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",)self.page = self.context.new_page()except Exception:self.stop()raisedef _log_login_state(self, label):try:1038 unmodified linesself.workspace_name = get_chatgpt_workspace_name()self.start_with_session(session_token, self.account_id, self.workspace_name)def is_started(self):return bool(self.browser or self.http_transport)def _build_api_headers(self, include_auth=True):raw_headers = {"Content-Type": "application/json","chatgpt-account-id": self.account_id,"oai-device-id": self.oai_device_id,"oai-language": "en-US",}if include_auth and self.access_token:raw_headers["authorization"] = f"Bearer {self.access_token}"# Browser fetch headers must be ISO-8859-1 (Latin1). Sanitize here so# Playwright and optional HTTP transports share the Round 11 header fix.headers = {}for key, value in raw_headers.items():if value is None:continueif isinstance(value, bytes):value = value.decode("ascii", errors="replace")else:value = str(value)sanitized = value.encode("latin-1", errors="replace").decode("latin-1")if sanitized != value:logger.warning("[ChatGPT] _api_fetch header %s 含非 ISO-8859-1 字符已被替换: %r -> %r",key,value[:60],sanitized[:60],)headers[key] = sanitizedreturn headersdef _start_transport_session(self, session_token):self.http_transport = build_chatgpt_transport(session_token=session_token,account_id=self.account_id,oai_device_id=self.oai_device_id,)if self.http_transport:self.transport_name = getattr(self.http_transport, "name", "curl_cffi")logger.info("[ChatGPT] Team API transport: %s", self.transport_name)return Truereturn False@staticmethoddef _transport_body_looks_like_html(body):text = str(body or "").lower()return "<html" in text or "<!doctype" in text or "<body" in textdef _transport_response_requires_browser_fallback(self, response):if not isinstance(response, dict):return Truestatus = int(response.get("status") or 0)body = response.get("body", "")if status <= 0 or status >= 500:return Trueif not self._transport_body_looks_like_html(body):return Falselower = str(body or "").lower()return any(marker in lowerfor marker in ("verify you are human","cloudflare","challenge","auth/login","log in","unable to load site",))def _start_browser_session(self, session_token):self._launch_browser()logger.info("[ChatGPT] 访问 chatgpt.com 过 Cloudflare...")self.page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=60000)3 unmodified linesself._fetch_access_token()self._auto_detect_workspace()def _ensure_browser_session(self):if self.browser:returnif not self.session_token:raise RuntimeError("缺少 session_token,无法回退到 Playwright transport")self._start_browser_session(self.session_token)def _fetch_access_token_via_transport(self, allow_bearer_file=True):if not getattr(self, "http_transport", None):return Nonetry:result = self.http_transport.request("GET","/api/auth/session",headers={"Accept": "application/json, text/plain, */*","oai-device-id": self.oai_device_id,},)except Exception as exc:logger.warning("[ChatGPT] curl_cffi 获取 access token 失败: %s", exc)result = Noneif result and int(result.get("status") or 0) == 200:try:data = json.loads(result.get("body") or "{}")except Exception:data = {}if "accessToken" in data:self.access_token = data["accessToken"]logger.info("[ChatGPT] 已通过 curl_cffi 获取 access token")return "curl_cffi"if allow_bearer_file:bearer_file = BASE_DIR / "bearer_token"if bearer_file.exists():self.access_token = read_text(bearer_file).strip()logger.info("[ChatGPT] 从 bearer_token 文件加载 access token")return "file"return Nonedef _auto_detect_workspace_via_transport(self):if self.workspace_name or not getattr(self, "http_transport", None) or not self.account_id:return self.workspace_nametry:result = self.http_transport.request("GET",f"/backend-api/accounts/{self.account_id}/settings",headers=self._build_api_headers(),)except Exception as exc:logger.warning("[ChatGPT] curl_cffi 自动检测 workspace 失败: %s", exc)return ""if int(result.get("status") or 0) != 200:return ""try:data = json.loads(result.get("body") or "{}")except Exception:return ""workspace_name = (data or {}).get("workspace_name", "") if isinstance(data, dict) else ""if workspace_name:self.workspace_name = workspace_nameupdate_admin_state(workspace_name=self.workspace_name, account_id=self.account_id)logger.info("[ChatGPT] 自动检测到 workspace 名称: %s", self.workspace_name)return self.workspace_namedef start_with_session(self, session_token, account_id, workspace_name="", require_browser=False):"""用指定的 session/account 启动浏览器上下文。"""if not session_token:raise FileNotFoundError("缺少会话信息")self.stop()self.account_id = account_id or ""self.workspace_name = workspace_name or ""self.session_token = session_tokenself.access_token = Noneif not self.account_id:raise RuntimeError("缺少 workspace/account ID")if not require_browser and self._start_transport_session(session_token):token_source = self._fetch_access_token_via_transport()if token_source:self._auto_detect_workspace_via_transport()returnlogger.warning("[ChatGPT] curl_cffi 未能直接获取 access token,回退 Playwright transport")if getattr(self, "http_transport", None):self.http_transport.close()self.http_transport = Noneself.transport_name = Noneself._start_browser_session(session_token)def _auto_detect_workspace(self):if self.workspace_name:return self.workspace_name84 unmodified lineslogger.warning("[ChatGPT] 未能获取 access token,将尝试无 token 调用")return Nonedef _browser_api_fetch(self, method, path, body=None):if not self.page:raise RuntimeError("Playwright 页面未初始化")js_code = """async ([method, url, headers, body]) => {try {const opts = { method, headers };8 unmodified linesreturn self.page.evaluate(js_code,[method, f"https://chatgpt.com{path}", self._build_api_headers(), json.dumps(body) if body else None],)def _direct_api_fetch(self, method, path, body=None):if not getattr(self, "http_transport", None):raise RuntimeError("curl_cffi transport 未初始化")response = self.http_transport.request(method,path,headers=self._build_api_headers(),body=body,)status = int(response.get("status") or 0)body_text = str(response.get("body") or "")lower_body = body_text.lower()if status == 401 and path != "/api/auth/session":refreshed = self._fetch_access_token_via_transport(allow_bearer_file=False)if refreshed:response = self.http_transport.request(method,path,headers=self._build_api_headers(),body=body,)status = int(response.get("status") or 0)body_text = str(response.get("body") or "")lower_body = body_text.lower()if self._transport_response_requires_browser_fallback(response):logger.warning("[ChatGPT] curl_cffi 返回异常响应,回退 Playwright transport")self._ensure_browser_session()return self._browser_api_fetch(method, path, body)if status == 401 and ("access token is missing" in lower_body or self._transport_body_looks_like_html(body_text)):logger.warning("[ChatGPT] curl_cffi 鉴权异常,回退 Playwright transport")self._ensure_browser_session()return self._browser_api_fetch(method, path, body)return responsedef _api_fetch(self, method, path, body=None):if getattr(self, "http_transport", None):return self._direct_api_fetch(method, path, body)if not self.page and self.session_token:self._ensure_browser_session()return self._browser_api_fetch(method, path, body)# POST /invites 失败时的重试间隔(秒)。rate_limited / network 类错误按此序列退避。_INVITE_POST_RETRY_DELAYS = (5, 15)254 unmodified linesdef stop(self):try:if getattr(self, "http_transport", None):self.http_transport.close()except Exception:passclose_playwright_objects(page=self.page,context=self.context,browser=self.browser,playwright=self.playwright,logger=logger,label="ChatGPTTeamAPI.stop",)self.browser = Noneself.context = Noneself.page = Noneself.playwright = Noneself.http_transport = Noneself.transport_name = None
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Optional lightweight HTTP transport for ChatGPT Team API calls."""
from __future__ import annotations
import jsonimport logging
from autoteam.config import ( get_chatgpt_api_http_timeout, get_chatgpt_api_impersonate, get_chatgpt_api_transport, get_chatgpt_http_proxy_url,)
logger = logging.getLogger(__name__)
def _build_session_cookie_pairs(session_token: str) -> list[tuple[str, str]]: token = str(session_token or "") if not token: return [] if len(token) > 3800: return [ ("__Secure-next-auth.session-token.0", token[:3800]), ("__Secure-next-auth.session-token.1", token[3800:]), ] return [("__Secure-next-auth.session-token", token)]
class CurlCffiChatGPTTransport: name = "curl_cffi"
def __init__(self, *, session_token: str, account_id: str = "", oai_device_id: str = ""): from curl_cffi import requests as curl_requests
self._timeout = get_chatgpt_api_http_timeout() self._session = curl_requests.Session(impersonate=get_chatgpt_api_impersonate()) self._session.headers.update( { "accept": "application/json, text/plain, */*", "origin": "https://chatgpt.com", "referer": "https://chatgpt.com/", } )
proxy_url = get_chatgpt_http_proxy_url() if proxy_url: self._session.proxies = {"http": proxy_url, "https": proxy_url}
for name, value in _build_session_cookie_pairs(session_token): self._session.cookies.set(name, value, domain="chatgpt.com", path="/", secure=True) if account_id: self._session.cookies.set("_account", account_id, domain="chatgpt.com", path="/") if oai_device_id: self._session.cookies.set("oai-did", oai_device_id, domain="chatgpt.com", path="/")
def request(self, method: str, path: str, *, headers: dict | None = None, body=None) -> dict[str, object]: url = path if str(path).startswith("http") else f"https://chatgpt.com{path}" request_kwargs = { "headers": headers or {}, "timeout": self._timeout, "allow_redirects": True, } if body is not None: if isinstance(body, (str, bytes)): request_kwargs["data"] = body else: request_kwargs["data"] = json.dumps(body, ensure_ascii=False)
response = self._session.request(method.upper(), url, **request_kwargs) return {"status": int(response.status_code), "body": response.text}
def close(self) -> None: try: self._session.close() except Exception: pass
def build_chatgpt_transport(*, session_token: str, account_id: str = "", oai_device_id: str = ""): mode = get_chatgpt_api_transport() if mode == "playwright": return None
try: return CurlCffiChatGPTTransport( session_token=session_token, account_id=account_id, oai_device_id=oai_device_id, ) except ModuleNotFoundError: if mode == "curl_cffi": logger.warning("[ChatGPT] CHATGPT_API_TRANSPORT=curl_cffi 但 curl_cffi 未安装,回退 Playwright") else: logger.info("[ChatGPT] curl_cffi 未安装,继续使用 Playwright transport") return None except Exception as exc: logger.warning("[ChatGPT] 初始化 curl_cffi transport 失败: %s", exc) return None2600 unmodified lines26012602260326042605260626072600 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIself.chatgpt = ChatGPTTeamAPI()self.chatgpt.start_with_session(self.session_token, self.account_id, self.workspace_name)self.page = self.chatgpt.context.new_page()self._attach_callback_listeners()self._inject_auth_cookies()2600 unmodified lines2601260226032604260526062607260826092610261126122600 unmodified linesfrom autoteam.chatgpt_api import ChatGPTTeamAPIself.chatgpt = ChatGPTTeamAPI()self.chatgpt.start_with_session(self.session_token,self.account_id,self.workspace_name,require_browser=True,)self.page = self.chatgpt.context.new_page()self._attach_callback_listeners()self._inject_auth_cookies()
1 unmodified line234567814 unmodified lines23242526272896 unmodified lines1251261271281291301 unmodified lineimport osfrom pathlib import Pathfrom urllib.parse import unquote, urlsplitfrom autoteam.textio import parse_env_line, parse_env_value, read_text14 unmodified linesreturn int(parse_env_value(os.environ.get(name, str(default))))# CloudMail 配置CLOUDMAIL_BASE_URL = os.environ.get("CLOUDMAIL_BASE_URL", "")CLOUDMAIL_EMAIL = os.environ.get("CLOUDMAIL_EMAIL", "")96 unmodified linesreturn proxydef get_playwright_launch_options():"""统一的 Playwright Chromium 启动参数。"""options = {1 unmodified line234567814 unmodified lines23242526272829303132333435363738394096 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified lineimport osfrom pathlib import Pathfrom urllib.parse import quote, unquote, urlsplitfrom autoteam.textio import parse_env_line, parse_env_value, read_text14 unmodified linesreturn int(parse_env_value(os.environ.get(name, str(default))))def _get_str_env(name: str, default: str = "") -> str:value = parse_env_value(os.environ.get(name, default))return str(value).strip()def _normalize_chatgpt_api_transport(value: str) -> str:mode = str(value or "").strip().lower()if mode in {"auto", "playwright", "curl_cffi"}:return modereturn "playwright"# CloudMail 配置CLOUDMAIL_BASE_URL = os.environ.get("CLOUDMAIL_BASE_URL", "")CLOUDMAIL_EMAIL = os.environ.get("CLOUDMAIL_EMAIL", "")96 unmodified linesreturn proxydef get_chatgpt_api_transport() -> str:# Match autoteam-1: Team backend API reads may use HTTP-first transport by default.# Browser/OAuth flows must opt out with require_browser=True at the call site.return _normalize_chatgpt_api_transport(_get_str_env("CHATGPT_API_TRANSPORT", "auto"))def get_chatgpt_api_http_timeout() -> int:return max(5, _get_int_env("CHATGPT_API_HTTP_TIMEOUT", 60))def get_chatgpt_api_impersonate() -> str:return _get_str_env("CHATGPT_API_IMPERSONATE", "chrome136") or "chrome136"def get_chatgpt_http_proxy_url() -> str:proxy_url = _get_str_env("PLAYWRIGHT_PROXY_URL", "")if proxy_url:return proxy_urlproxy_server = _get_str_env("PLAYWRIGHT_PROXY_SERVER", "")if not proxy_server:return ""username = _get_str_env("PLAYWRIGHT_PROXY_USERNAME", "")password = _get_str_env("PLAYWRIGHT_PROXY_PASSWORD", "")if not (username or password):return proxy_serverparsed = urlsplit(proxy_server)if not parsed.scheme or not parsed.hostname:return proxy_serverhost = _format_proxy_host(parsed.hostname)auth = quote(username, safe="")if password:auth = f"{auth}:{quote(password, safe='')}"proxy = f"{parsed.scheme}://{auth}@{host}"if parsed.port:proxy = f"{proxy}:{parsed.port}"return proxydef get_playwright_launch_options():"""统一的 Playwright Chromium 启动参数。"""options = {
153 unmodified lines154155156157158159160161162163497 unmodified lines661662663664665666667307 unmodified lines975976977978979980981547 unmodified lines15291530153115321533153415351216 unmodified lines2752275327542755275627572758968 unmodified lines37273728372937303731373237337 unmodified lines374137423743374437453746374727 unmodified lines3775377637773778377937803781356 unmodified lines41384139414041414142414341444 unmodified lines414941504151415241534154415524 unmodified lines418041814182418341844185418617 unmodified lines42044205420642074208420942101 unmodified line4212421342144215421642174218191 unmodified lines441044114412441344144415441684 unmodified lines450145024503450445054506450722 unmodified lines45304531453245334534453545366 unmodified lines454345444545454645474548454973 unmodified lines4623462446254626462746284629113 unmodified lines47434744474547464747474847494750475147524753475420 unmodified lines477547764777477847794780478131 unmodified lines4813481448154816481748184819280 unmodified lines510051015102510351045105510651073 unmodified lines51115112511351145115511651171 unmodified line51195120512151225123512451254 unmodified lines5130513151325133513451355136177 unmodified lines5314531553165317531853195320532153225323532453255326153 unmodified linesdef _chatgpt_session_ready(chatgpt_api) -> bool:"""判断 chatgpt_api 是否处于"已启动浏览器"状态(上游 `.upstream/manager.py:84`)。本地 ChatGPTTeamAPI 没有 `is_started()` 方法,但有 `browser` 属性。getattr 容错保证未来上游加 `is_started()` 时自动适配。"""if not chatgpt_api:return False497 unmodified linesreturn resultneed_stop = Falseif not chatgpt_api or not getattr(chatgpt_api, "browser", None):try:chatgpt_api = ChatGPTTeamAPI()chatgpt_api.start()307 unmodified lines# 获取 Team 实际成员need_stop = Falseif not chatgpt_api or not chatgpt_api.browser:try:chatgpt_api = ChatGPTTeamAPI()chatgpt_api.start()547 unmodified linesexcept Exception as exc:logger.warning("[检查] pending 对账失败,跳过本轮清理: %s", exc)finally:if chatgpt and chatgpt.browser:chatgpt.stop()if deleted_pending:1216 unmodified lineslogger.warning("[直接注册] 检查 Team 成员失败: %s", exc)return Falsefinally:if chatgpt and chatgpt.browser:chatgpt.stop()968 unmodified lines# 先检查 pending invitesmail_client = _resolve_mail_client_or_default(mail_client, acc=acc)if chatgpt_api and chatgpt_api.browser:logger.info("[创建] 先检查 pending invites...")completed = _check_pending_invites(chatgpt_api,7 unmodified lines# 直接注册模式(不需要邀请)logger.info("[创建] 使用直接注册模式...")if chatgpt_api and chatgpt_api.browser:chatgpt_api.stop()return create_account_direct(mail_client,27 unmodified linesdef _cleanup_team_leftover(reason):"""OAuth 失败/plan 不对时,兜底 kick 账号,避免假 standby。"""try:if not chatgpt_api.browser:chatgpt_api.start()kick_status = remove_from_team(chatgpt_api, email, return_status=True)if kick_status == "removed":356 unmodified linescontinuelogger.info("[替换] 尝试复用 standby: %s", cand_email)if not chatgpt.browser:chatgpt.start()if reinvite_account(chatgpt, mail_client, acc):outcome["filled_by"] = cand_email4 unmodified lines# 4. 无可复用 standby → 创建新号logger.info("[替换] 无可复用 standby,创建新号补位...")if not chatgpt.browser:chatgpt.start()try:new_email = create_new_account(chatgpt, mail_client)24 unmodified linestry:return _replace_single(chatgpt, mail_client, email, reason=reason)finally:if chatgpt.browser:chatgpt.stop()try:sync_to_cpa()17 unmodified linestry:for email in emails:try:if not chatgpt.browser:chatgpt.start()out = _replace_single(chatgpt, mail_client, email, reason=trigger or "batch")outcomes.append({"email": email, **out})1 unmodified linelogger.error("[替换] %s 单个替换抛异常: %s", email, exc)outcomes.append({"email": email, "kicked": False, "filled_by": None, "error": f"exception: {exc}"})finally:if chatgpt.browser:chatgpt.stop()try:sync_to_cpa()191 unmodified linesdef ensure_chatgpt():nonlocal chatgptif not chatgpt or not chatgpt.browser:chatgpt = ChatGPTTeamAPI()chatgpt.start()return chatgpt84 unmodified linespreempt_candidates.append(acc)if preempt_candidates:logger.info("[2.5/5] 预测式抢先替换 %d 个即将耗尽的账号...", len(preempt_candidates))if not chatgpt or not chatgpt.browser:ensure_chatgpt()for acc in preempt_candidates:email = acc["email"]22 unmodified linesinitial_api_count = get_team_member_count(chatgpt)for acc in all_exhausted:email = acc["email"]if not chatgpt.browser:chatgpt.start()remove_status = remove_from_team(chatgpt, email, return_status=True)if remove_status in ("removed", "already_absent"):6 unmodified lineslogger.info("[3/5] %s → standby(远端已不存在)", email)else:logger.info("[3/5] 无需移出账号")if not chatgpt or not chatgpt.browser:ensure_chatgpt()api_count = get_team_member_count(chatgpt)logger.info(73 unmodified linescandidates = list(standby_list)def _chatgpt_provider():if not chatgpt or not chatgpt.browser:ensure_chatgpt()return chatgpt113 unmodified lineslogger.warning("[轮转] 收到取消请求,已创建 %d/%d 个新号", i, remaining)breaklogger.info("[5/5] 创建第 %d/%d 个...", i + 1, remaining)if not chatgpt or not chatgpt.browser:ensure_chatgpt()if create_new_account(chatgpt, ensure_mail()):current_count += 1if not chatgpt or not chatgpt.browser:ensure_chatgpt()final_count = get_team_member_count(chatgpt)# 双指标终止条件 (Round 12 S3 cherry-pick, 上游 `.upstream/manager.py` 终止条件):20 unmodified lines)finally:if chatgpt and chatgpt.browser:chatgpt.stop()# 所有操作完成后统一同步 CPA,避免中途同步导致 CPA 不可用logger.info("[轮转] 轮转完成,同步 CPA...")31 unmodified lineselse:logger.error("[添加] 添加失败")finally:if chatgpt.browser:chatgpt.stop()280 unmodified lineslogger.info("[填充] 跳过旧账号: %s(%s)", email, skip_reason)continuelogger.info("[填充] 复用旧账号: %s", email)# 确保 chatgpt 浏览器可用if not chatgpt.browser:chatgpt.start()added = reinvite_account(chatgpt, mail_client, reusable)if added:3 unmodified linesif not added:# 创建新账号logger.info("[填充] 创建新账号...")if not chatgpt.browser:chatgpt.start()added = create_new_account(chatgpt, mail_client)1 unmodified linelogger.warning("[填充] 本轮补位失败,第 %d/%d 个空缺仍未填上", i + 1, need)# 验证成员数if not chatgpt.browser:chatgpt.start()new_count = get_team_member_count(chatgpt)if new_count >= 0:4 unmodified linescmd_status()finally:if chatgpt.browser:chatgpt.stop()177 unmodified lineschatgpt = [None]def _ensure_chatgpt():if not chatgpt[0] or not chatgpt[0].browser:chatgpt[0] = ChatGPTTeamAPI()chatgpt[0].start()return chatgpt[0]def _stop_chatgpt():if chatgpt[0] and chatgpt[0].browser:try:chatgpt[0].stop()except Exception as exc:153 unmodified lines154155156157158159160161162163497 unmodified lines661662663664665666667307 unmodified lines975976977978979980981547 unmodified lines15291530153115321533153415351216 unmodified lines2752275327542755275627572758968 unmodified lines37273728372937303731373237337 unmodified lines374137423743374437453746374727 unmodified lines3775377637773778377937803781356 unmodified lines41384139414041414142414341444 unmodified lines414941504151415241534154415524 unmodified lines418041814182418341844185418617 unmodified lines42044205420642074208420942101 unmodified line4212421342144215421642174218191 unmodified lines441044114412441344144415441684 unmodified lines450145024503450445054506450722 unmodified lines45304531453245334534453545366 unmodified lines454345444545454645474548454973 unmodified lines4623462446254626462746284629113 unmodified lines47434744474547464747474847494750475147524753475420 unmodified lines477547764777477847794780478131 unmodified lines4813481448154816481748184819280 unmodified lines510051015102510351045105510651073 unmodified lines51115112511351145115511651171 unmodified line51195120512151225123512451254 unmodified lines5130513151325133513451355136177 unmodified lines5314531553165317531853195320532153225323532453255326153 unmodified linesdef _chatgpt_session_ready(chatgpt_api) -> bool:"""判断 chatgpt_api 是否处于可用 Team API session 状态。`CHATGPT_API_TRANSPORT=auto` 时可能只有 HTTP transport 而没有 browser,因此生命周期判断必须优先使用 `is_started()`,再回退到旧的 browser 字段。"""if not chatgpt_api:return False497 unmodified linesreturn resultneed_stop = Falseif not chatgpt_api or not _chatgpt_session_ready(chatgpt_api):try:chatgpt_api = ChatGPTTeamAPI()chatgpt_api.start()307 unmodified lines# 获取 Team 实际成员need_stop = Falseif not chatgpt_api or not _chatgpt_session_ready(chatgpt_api):try:chatgpt_api = ChatGPTTeamAPI()chatgpt_api.start()547 unmodified linesexcept Exception as exc:logger.warning("[检查] pending 对账失败,跳过本轮清理: %s", exc)finally:if chatgpt:chatgpt.stop()if deleted_pending:1216 unmodified lineslogger.warning("[直接注册] 检查 Team 成员失败: %s", exc)return Falsefinally:if chatgpt:chatgpt.stop()968 unmodified lines# 先检查 pending invitesmail_client = _resolve_mail_client_or_default(mail_client, acc=acc)if chatgpt_api and _chatgpt_session_ready(chatgpt_api):logger.info("[创建] 先检查 pending invites...")completed = _check_pending_invites(chatgpt_api,7 unmodified lines# 直接注册模式(不需要邀请)logger.info("[创建] 使用直接注册模式...")if chatgpt_api and _chatgpt_session_ready(chatgpt_api):chatgpt_api.stop()return create_account_direct(mail_client,27 unmodified linesdef _cleanup_team_leftover(reason):"""OAuth 失败/plan 不对时,兜底 kick 账号,避免假 standby。"""try:if not _chatgpt_session_ready(chatgpt_api):chatgpt_api.start()kick_status = remove_from_team(chatgpt_api, email, return_status=True)if kick_status == "removed":356 unmodified linescontinuelogger.info("[替换] 尝试复用 standby: %s", cand_email)if not _chatgpt_session_ready(chatgpt):chatgpt.start()if reinvite_account(chatgpt, mail_client, acc):outcome["filled_by"] = cand_email4 unmodified lines# 4. 无可复用 standby → 创建新号logger.info("[替换] 无可复用 standby,创建新号补位...")if not _chatgpt_session_ready(chatgpt):chatgpt.start()try:new_email = create_new_account(chatgpt, mail_client)24 unmodified linestry:return _replace_single(chatgpt, mail_client, email, reason=reason)finally:if chatgpt:chatgpt.stop()try:sync_to_cpa()17 unmodified linestry:for email in emails:try:if not _chatgpt_session_ready(chatgpt):chatgpt.start()out = _replace_single(chatgpt, mail_client, email, reason=trigger or "batch")outcomes.append({"email": email, **out})1 unmodified linelogger.error("[替换] %s 单个替换抛异常: %s", email, exc)outcomes.append({"email": email, "kicked": False, "filled_by": None, "error": f"exception: {exc}"})finally:if chatgpt:chatgpt.stop()try:sync_to_cpa()191 unmodified linesdef ensure_chatgpt():nonlocal chatgptif not chatgpt or not _chatgpt_session_ready(chatgpt):chatgpt = ChatGPTTeamAPI()chatgpt.start()return chatgpt84 unmodified linespreempt_candidates.append(acc)if preempt_candidates:logger.info("[2.5/5] 预测式抢先替换 %d 个即将耗尽的账号...", len(preempt_candidates))if not chatgpt or not _chatgpt_session_ready(chatgpt):ensure_chatgpt()for acc in preempt_candidates:email = acc["email"]22 unmodified linesinitial_api_count = get_team_member_count(chatgpt)for acc in all_exhausted:email = acc["email"]if not _chatgpt_session_ready(chatgpt):chatgpt.start()remove_status = remove_from_team(chatgpt, email, return_status=True)if remove_status in ("removed", "already_absent"):6 unmodified lineslogger.info("[3/5] %s → standby(远端已不存在)", email)else:logger.info("[3/5] 无需移出账号")if not chatgpt or not _chatgpt_session_ready(chatgpt):ensure_chatgpt()api_count = get_team_member_count(chatgpt)logger.info(73 unmodified linescandidates = list(standby_list)def _chatgpt_provider():if not chatgpt or not _chatgpt_session_ready(chatgpt):ensure_chatgpt()return chatgpt113 unmodified lineslogger.warning("[轮转] 收到取消请求,已创建 %d/%d 个新号", i, remaining)breaklogger.info("[5/5] 创建第 %d/%d 个...", i + 1, remaining)if not chatgpt or not _chatgpt_session_ready(chatgpt):ensure_chatgpt()if create_new_account(chatgpt, ensure_mail()):current_count += 1if not chatgpt or not _chatgpt_session_ready(chatgpt):ensure_chatgpt()final_count = get_team_member_count(chatgpt)# 双指标终止条件 (Round 12 S3 cherry-pick, 上游 `.upstream/manager.py` 终止条件):20 unmodified lines)finally:if chatgpt:chatgpt.stop()# 所有操作完成后统一同步 CPA,避免中途同步导致 CPA 不可用logger.info("[轮转] 轮转完成,同步 CPA...")31 unmodified lineselse:logger.error("[添加] 添加失败")finally:if chatgpt:chatgpt.stop()280 unmodified lineslogger.info("[填充] 跳过旧账号: %s(%s)", email, skip_reason)continuelogger.info("[填充] 复用旧账号: %s", email)# 确保 Team API session 可用;auto transport 不一定有 browser。if not _chatgpt_session_ready(chatgpt):chatgpt.start()added = reinvite_account(chatgpt, mail_client, reusable)if added:3 unmodified linesif not added:# 创建新账号logger.info("[填充] 创建新账号...")if not _chatgpt_session_ready(chatgpt):chatgpt.start()added = create_new_account(chatgpt, mail_client)1 unmodified linelogger.warning("[填充] 本轮补位失败,第 %d/%d 个空缺仍未填上", i + 1, need)# 验证成员数if not _chatgpt_session_ready(chatgpt):chatgpt.start()new_count = get_team_member_count(chatgpt)if new_count >= 0:4 unmodified linescmd_status()finally:if chatgpt:chatgpt.stop()177 unmodified lineschatgpt = [None]def _ensure_chatgpt():if not chatgpt[0] or not _chatgpt_session_ready(chatgpt[0]):chatgpt[0] = ChatGPTTeamAPI()chatgpt[0].start()return chatgpt[0]def _stop_chatgpt():if chatgpt[0]:try:chatgpt[0].stop()except Exception as exc:
1234567891011121314151617181920212223242526272829303132333435363738"""Utilities for consistently releasing Playwright resources."""
from __future__ import annotations
from collections.abc import Callablefrom typing import Any
def _call_close(obj: Any, method_name: str) -> None: method: Callable[[], Any] | None = getattr(obj, method_name, None) if callable(method): method()
def close_playwright_objects( page: Any = None, context: Any = None, browser: Any = None, playwright: Any = None, *, logger: Any = None, label: str = "playwright",) -> None: """Best-effort close for Playwright objects in dependency order."""
for name, obj, method_name in ( ("page", page, "close"), ("context", context, "close"), ("browser", browser, "close"), ("playwright", playwright, "stop"), ): if obj is None: continue try: _call_close(obj, method_name) except Exception as exc: if logger is not None: logger.debug("[%s] close %s failed: %s", label, name, exc)123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Short-lived Playwright probe process.
Runs browser probes that are allowed to be killed as a whole process tree by theparent process. This keeps periodic background checks from accumulating stuckPlaywright / Chromium children."""
from __future__ import annotations
import jsonimport loggingimport sys
logging.basicConfig(level=logging.WARNING)
def _probe_team_member_count() -> dict[str, int]: from autoteam.chatgpt_api import ChatGPTTeamAPI from autoteam.manager import get_team_member_count
chatgpt = ChatGPTTeamAPI() try: chatgpt.start() return {"count": int(get_team_member_count(chatgpt))} finally: chatgpt.stop()
def main() -> None: action = (sys.argv[1] if len(sys.argv) > 1 else "").strip().lower()
try: if action == "team-member-count": result = _probe_team_member_count() else: raise RuntimeError(f"unknown probe action: {action or 'empty'}") except Exception as exc: print(json.dumps({"error": str(exc)}, ensure_ascii=False)) raise SystemExit(1) from exc
print(json.dumps(result, ensure_ascii=False))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""Lightweight runtime resource probes for the AutoTeam service container."""
from __future__ import annotations
import gcimport osimport subprocessfrom pathlib import Pathfrom typing import Any
PROC_SELF_STATUS = Path("/proc/self/status")CGROUP_MEMORY_CURRENT = Path("/sys/fs/cgroup/memory.current")CGROUP_MEMORY_MAX = Path("/sys/fs/cgroup/memory.max")CGROUP_PIDS_CURRENT = Path("/sys/fs/cgroup/pids.current")CGROUP_PIDS_MAX = Path("/sys/fs/cgroup/pids.max")
def _read_text(path: Path) -> str | None: try: return path.read_text(encoding="utf-8").strip() except OSError: return None
def _read_int(path: Path) -> int | None: text = _read_text(path) if not text or text == "max": return None try: return int(text) except ValueError: return None
def _read_proc_rss_bytes() -> int | None: text = _read_text(PROC_SELF_STATUS) if not text: return None for line in text.splitlines(): if not line.startswith("VmRSS:"): continue parts = line.split() if len(parts) >= 2: try: return int(parts[1]) * 1024 except ValueError: return None return None
def _process_rows() -> list[str]: try: result = subprocess.run( ["ps", "-eo", "state=,comm=,args="], check=False, capture_output=True, text=True, timeout=2, ) except (OSError, subprocess.SubprocessError): return [] if result.returncode != 0: return [] return [line.strip() for line in result.stdout.splitlines() if line.strip()]
def _count_browser_processes(rows: list[str]) -> dict[str, int]: total = 0 live = 0 zombie = 0 for row in rows: lower = row.lower() if "chrome" not in lower and "chromium" not in lower and "playwright" not in lower: continue total += 1 if row[:1] == "Z": zombie += 1 else: live += 1 return { "browser_process_total": total, "browser_process_live": live, "browser_process_zombie": zombie, }
def _bytes_to_mb(value: int | None) -> float | None: if value is None: return None return round(value / 1024 / 1024, 1)
def _float_env(name: str, default: float) -> float: try: return float(os.environ.get(name, str(default))) except ValueError: return default
def _int_env(name: str, default: int) -> int: try: return int(os.environ.get(name, str(default))) except ValueError: return default
def collect_runtime_resource_snapshot() -> dict[str, Any]: """Collect memory and browser-process counters without external dependencies."""
rss_bytes = _read_proc_rss_bytes() memory_current_bytes = _read_int(CGROUP_MEMORY_CURRENT) memory_max_bytes = _read_int(CGROUP_MEMORY_MAX) pids_current = _read_int(CGROUP_PIDS_CURRENT) pids_max = _read_int(CGROUP_PIDS_MAX) process_counts = _count_browser_processes(_process_rows())
memory_usage_ratio = None if memory_current_bytes is not None and memory_max_bytes: memory_usage_ratio = memory_current_bytes / memory_max_bytes
return { "rss_mb": _bytes_to_mb(rss_bytes), "cgroup_memory_mb": _bytes_to_mb(memory_current_bytes), "cgroup_memory_limit_mb": _bytes_to_mb(memory_max_bytes), "cgroup_memory_usage_ratio": memory_usage_ratio, "pids_current": pids_current, "pids_max": pids_max, **process_counts, }
def _fmt_mb(value: float | None) -> str: if value is None: return "unknown" return f"{value:.1f}MiB"
def _fmt_ratio(value: float | None) -> str: if value is None: return "unknown" return f"{value * 100:.1f}%"
def log_runtime_resource_snapshot(logger: Any, *, label: str = "runtime") -> dict[str, Any]: """Log a resource snapshot and run GC when memory is near the cgroup limit."""
snapshot = collect_runtime_resource_snapshot() logger.info( "[资源] %s rss=%s cgroup=%s/%s usage=%s pids=%s/%s browser_live=%d browser_zombie=%d", label, _fmt_mb(snapshot["rss_mb"]), _fmt_mb(snapshot["cgroup_memory_mb"]), _fmt_mb(snapshot["cgroup_memory_limit_mb"]), _fmt_ratio(snapshot["cgroup_memory_usage_ratio"]), snapshot["pids_current"] if snapshot["pids_current"] is not None else "unknown", snapshot["pids_max"] if snapshot["pids_max"] is not None else "unknown", snapshot["browser_process_live"], snapshot["browser_process_zombie"], )
ratio = snapshot["cgroup_memory_usage_ratio"] warn_ratio = _float_env("AUTOTEAM_MEMORY_WARN_RATIO", 0.85) if ratio is not None and ratio >= warn_ratio: collected = gc.collect() logger.warning( "[资源] %s cgroup memory usage %s >= %.1f%%, gc.collect reclaimed %d objects", label, _fmt_ratio(ratio), warn_ratio * 100, collected, )
zombie_threshold = _int_env("AUTOTEAM_ZOMBIE_WARN_THRESHOLD", 20) if snapshot["browser_process_zombie"] >= zombie_threshold: logger.warning( "[资源] %s browser zombie processes=%d >= %d; container init/reaper should be enabled", label, snapshot["browser_process_zombie"], zombie_threshold, )
return snapshot10 unmodified lines11121314151617181920212223242522 unmodified lines4849505152539 unmodified lines6364656667686970717273747576777810 unmodified linesgenerate **once per account** and pass through both ``register_with_invite``and ``login_codex_via_browser``, so the two pages see consistent data.Backward-compat: :class:`SignupProfile` is created with random_* helpers from:mod:`autoteam.identity` so behaviour matches the previous fork's per-callrandomness — only the *consistency across the two stages* is new."""from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom autoteam.identity import random_age, random_birthday, random_full_name@dataclass(frozen=True)22 unmodified lines"""Age as a string (the about-you age input expects a string)."""return self.age# ---------------------------------------------------- spinbutton helperdef positional_birthday_orders(self) -> list[list[str]]:"""Yield candidate orderings for the React-Aria DateField spinbuttons.9 unmodified linesreturn [[bday.get("year", ""), bday.get("month", ""), bday.get("day", "")]]def generate_signup_profile() -> SignupProfile:"""Build a fresh :class:`SignupProfile` for a new account."""return SignupProfile(full_name=random_full_name(),birthday=random_birthday(),age=random_age(),)__all__ = ["SignupProfile","generate_signup_profile",]10 unmodified lines111213141516171819202122232425262728293022 unmodified lines5354555657585960616263649 unmodified lines747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713810 unmodified linesgenerate **once per account** and pass through both ``register_with_invite``and ``login_codex_via_browser``, so the two pages see consistent data.Backward-compat: :class:`SignupProfile` keeps the existing field shape used bycallers. The birthday and age are generated together so the same snapshot isalso internally self-consistent."""from __future__ import annotationsimport randomfrom dataclasses import dataclass, fieldfrom datetime import date, timedeltafrom autoteam.identity import random_full_nameMIN_SIGNUP_AGE = 22MAX_SIGNUP_AGE = 42@dataclass(frozen=True)22 unmodified lines"""Age as a string (the about-you age input expects a string)."""return self.age@propertydef birth_date(self) -> date:"""Birthday as a ``date`` for validation and tests."""bday = self.birthday or {}return date(int(bday["year"]), int(bday["month"]), int(bday["day"]))# ---------------------------------------------------- spinbutton helperdef positional_birthday_orders(self) -> list[list[str]]:"""Yield candidate orderings for the React-Aria DateField spinbuttons.9 unmodified linesreturn [[bday.get("year", ""), bday.get("month", ""), bday.get("day", "")]]def calculate_age(birth_date: date, today: date) -> int:years = today.year - birth_date.yearif (today.month, today.day) < (birth_date.month, birth_date.day):years -= 1return yearsdef _replace_year_safe(value: date, year: int) -> date:try:return value.replace(year=year)except ValueError:return value.replace(year=year, day=28)def _birthdate_bounds(today: date,*,min_age: int = MIN_SIGNUP_AGE,max_age: int = MAX_SIGNUP_AGE,) -> tuple[date, date]:oldest_allowed = _replace_year_safe(today, today.year - (max_age + 1)) + timedelta(days=1)youngest_allowed = _replace_year_safe(today, today.year - min_age)return oldest_allowed, youngest_alloweddef _birthday_dict(birth_date: date) -> dict[str, str]:return {"year": f"{birth_date.year:04d}","month": f"{birth_date.month:02d}","day": f"{birth_date.day:02d}",}def generate_signup_profile(*,today: date | None = None,rng: random.Random | random.SystemRandom | None = None,) -> SignupProfile:"""Build a fresh :class:`SignupProfile` for a new account."""today = today or date.today()rng = rng or random.SystemRandom()oldest_allowed, youngest_allowed = _birthdate_bounds(today)offset = rng.randrange((youngest_allowed - oldest_allowed).days + 1)birth_date = oldest_allowed + timedelta(days=offset)age = calculate_age(birth_date, today)if not (MIN_SIGNUP_AGE <= age <= MAX_SIGNUP_AGE):raise ValueError(f"generated invalid signup age {age} for birth date {birth_date.isoformat()}")return SignupProfile(full_name=random_full_name(),birthday=_birthday_dict(birth_date),age=str(age),)__all__ = ["MAX_SIGNUP_AGE","MIN_SIGNUP_AGE","SignupProfile","calculate_age","generate_signup_profile",]
19 unmodified lines202122232425108 unmodified lines13413513613713813914014114214314414530 unmodified lines1761771781791801811 unmodified line18318418518618718818919019119 unmodified linesfrom fastapi.testclient import TestClientREPO_ROOT = Path(__file__).resolve().parents[2]# ---------------------------------------------------------------------------108 unmodified linessave_accounts,)from autoteam.api import app # noqa: F401from autoteam.manager import sync_account_states # noqa: F401# 简单的契约校验 — 函数应可调用、状态常量应是字符串assert callable(load_accounts)assert callable(save_accounts)assert callable(sync_account_states)for const in (STATUS_ACTIVE,STATUS_EXHAUSTED,30 unmodified linesassert "BUILD_TIME: ${BUILD_TIME:-unknown}" in composedef test_entrypoint_contains_self_check() -> None:"""entrypoint 必须包含 self-check + crash-loop 兜底。"""1 unmodified lineassert "[self-check]" in entrypointassert "from autoteam.api import app" in entrypointassert "from autoteam.accounts import" in entrypointassert "exit 1" in entrypoint, "self-check 失败必须 exit 1 触发 crash-loop"def test_pyproject_has_ruff_config() -> None:"""pyproject.toml 必须配 [tool.ruff.lint] 三条规则。"""19 unmodified lines202122232425262728293031108 unmodified lines14014114214314414514614714814915015115215315415515615715815930 unmodified lines1901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242251 unmodified line22722822923023123223323423523623723823924024124224324424524624724824925025125225319 unmodified linesfrom fastapi.testclient import TestClientREPO_ROOT = Path(__file__).resolve().parents[2]BASH_EXE = Path("C:/Program Files/Git/bin/bash.exe")if not BASH_EXE.exists():BASH_EXE = Path("C:/Program Files/Git/usr/bin/bash.exe")if not BASH_EXE.exists():detected_bash = shutil.which("bash")BASH_EXE = Path(detected_bash) if detected_bash else Path("bash")# ---------------------------------------------------------------------------108 unmodified linessave_accounts,)from autoteam.api import app # noqa: F401from autoteam.chatgpt_transport import build_chatgpt_transport # noqa: F401from autoteam.manager import sync_account_states # noqa: F401from autoteam.playwright_lifecycle import close_playwright_objects # noqa: F401from autoteam.playwright_probe import main as playwright_probe_main # noqa: F401from autoteam.runtime_resources import collect_runtime_resource_snapshot # noqa: F401# 简单的契约校验 — 函数应可调用、状态常量应是字符串assert callable(load_accounts)assert callable(save_accounts)assert callable(sync_account_states)assert callable(collect_runtime_resource_snapshot)assert callable(close_playwright_objects)assert callable(playwright_probe_main)assert callable(build_chatgpt_transport)for const in (STATUS_ACTIVE,STATUS_EXHAUSTED,30 unmodified linesassert "BUILD_TIME: ${BUILD_TIME:-unknown}" in composedef test_compose_declares_runtime_safety_bounds() -> None:"""0515 hardening: compose must keep browser/container resource boundaries."""compose = (REPO_ROOT / "docker-compose.yml").read_text(encoding="utf-8")assert "init: true" in composeassert 'shm_size: "1gb"' in composeassert 'mem_limit: "2g"' in composeassert 'memswap_limit: "2g"' in composeassert "pids_limit: 768" in composeassert 'AUTOTEAM_MEMORY_WARN_RATIO: "0.85"' in composeassert 'AUTOTEAM_ZOMBIE_WARN_THRESHOLD: "5"' in composeassert "healthcheck:" in composeassert "curl -fsS http://127.0.0.1:8787/api/version" in composedef test_dockerfile_fast_preserves_runtime_contracts() -> None:"""Dockerfile.fast is allowed only if it preserves fingerprint and self-check paths."""dockerfile = (REPO_ROOT / "Dockerfile.fast").read_text(encoding="utf-8")assert "FROM autoteam:latest" in dockerfileassert "ARG GIT_SHA" in dockerfileassert "ARG BUILD_TIME" in dockerfileassert "ENV AUTOTEAM_GIT_SHA" in dockerfileassert "ENV AUTOTEAM_BUILD_TIME" in dockerfileassert "org.opencontainers.image.revision" in dockerfileassert "COPY docker-entrypoint.sh /docker-entrypoint.sh" in dockerfileassert "sed -i 's/\\r$//'" in dockerfileassert 'ENTRYPOINT ["/docker-entrypoint.sh"]' in dockerfiledef test_entrypoint_contains_self_check() -> None:"""entrypoint 必须包含 self-check + crash-loop 兜底。"""1 unmodified lineassert "[self-check]" in entrypointassert "from autoteam.api import app" in entrypointassert "from autoteam.accounts import" in entrypointassert "from autoteam.runtime_resources import collect_runtime_resource_snapshot" in entrypointassert "from autoteam.playwright_lifecycle import close_playwright_objects" in entrypointassert "from autoteam.playwright_probe import main as playwright_probe_main" in entrypointassert "from autoteam.chatgpt_transport import build_chatgpt_transport" in entrypointassert "exit 1" in entrypoint, "self-check 失败必须 exit 1 触发 crash-loop"def test_entrypoint_shell_syntax_is_valid() -> None:"""The self-check heredoc must remain valid after Dockerfile CRLF normalization."""proc = subprocess.run([str(BASH_EXE), "-lc", "tr -d '\\r' < docker-entrypoint.sh | bash -n"],capture_output=True,text=True,encoding="utf-8",errors="replace",cwd=REPO_ROOT,)assert proc.returncode == 0, proc.stderrdef test_pyproject_has_ruff_config() -> None:"""pyproject.toml 必须配 [tool.ruff.lint] 三条规则。"""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155import threading
import pytest
from autoteam import api, chatgpt_api
def test_launch_browser_stops_playwright_when_browser_launch_fails(tmp_path, monkeypatch): class FakePlaywright: def __init__(self): self.stopped = False self.chromium = self
def launch(self, **_kwargs): raise RuntimeError("proxy launch failed")
def stop(self): self.stopped = True
class FakeSyncPlaywright: def __init__(self, playwright): self._playwright = playwright
def start(self): return self._playwright
fake_playwright = FakePlaywright() monkeypatch.setattr(chatgpt_api, "SCREENSHOT_DIR", tmp_path) monkeypatch.setattr(chatgpt_api, "get_playwright_launch_options", lambda: {"proxy": {"server": "http://proxy"}}) monkeypatch.setattr(chatgpt_api, "sync_playwright", lambda: FakeSyncPlaywright(fake_playwright))
client = chatgpt_api.ChatGPTTeamAPI()
with pytest.raises(RuntimeError, match="proxy launch failed"): client._launch_browser()
assert fake_playwright.stopped is True assert client.playwright is None assert client.browser is None assert client.context is None assert client.page is None
def test_chatgpt_stop_closes_page_context_browser_and_playwright(): calls = []
class FakeClosable: def __init__(self, name): self.name = name
def close(self): calls.append(f"close:{self.name}")
class FakePlaywright: def stop(self): calls.append("stop:playwright")
client = chatgpt_api.ChatGPTTeamAPI() client.page = FakeClosable("page") client.context = FakeClosable("context") client.browser = FakeClosable("browser") client.playwright = FakePlaywright()
client.stop() client.stop()
assert calls == ["close:page", "close:context", "close:browser", "stop:playwright"] assert client.page is None assert client.context is None assert client.browser is None assert client.playwright is None
def test_post_admin_login_start_stops_api_when_begin_login_fails(monkeypatch): instances = []
class FakeChatGPTTeamAPI: def __init__(self): self.stopped = False instances.append(self)
def begin_admin_login(self, _email): raise RuntimeError("proxy launch failed")
def stop(self): self.stopped = True
monkeypatch.setattr(api, "_playwright_lock", threading.Lock()) monkeypatch.setattr(api, "_admin_login_api", None) monkeypatch.setattr(api, "_admin_login_step", None) monkeypatch.setattr(api._pw_executor, "run", lambda func, *args, **kwargs: func(*args, **kwargs)) monkeypatch.setattr("autoteam.chatgpt_api.ChatGPTTeamAPI", FakeChatGPTTeamAPI)
with pytest.raises(api.HTTPException) as exc: api.post_admin_login_start(api.AdminEmailParams(email="admin@example.com"))
assert exc.value.status_code == 400 assert "proxy launch failed" in str(exc.value.detail) assert len(instances) == 1 assert instances[0].stopped is True assert api._admin_login_api is None assert api._playwright_lock.locked() is False
def test_get_team_members_stops_chatgpt_when_start_fails(monkeypatch): instances = []
class FakeChatGPTTeamAPI: def __init__(self): self.stopped = False instances.append(self)
def start(self): raise RuntimeError("http proxy failed")
def stop(self): self.stopped = True
monkeypatch.setattr(api, "_playwright_lock", threading.Lock()) monkeypatch.setattr(api._pw_executor, "run", lambda func, *args, **kwargs: func(*args, **kwargs)) monkeypatch.setattr("autoteam.admin_state.get_admin_session_token", lambda: "session") monkeypatch.setattr("autoteam.admin_state.get_chatgpt_account_id", lambda: "acc-1") monkeypatch.setattr("autoteam.chatgpt_api.ChatGPTTeamAPI", FakeChatGPTTeamAPI)
with pytest.raises(api.HTTPException) as exc: api.get_team_members()
assert exc.value.status_code == 502 assert "http proxy failed" in str(exc.value.detail) assert len(instances) == 1 assert instances[0].stopped is True assert api._playwright_lock.locked() is False
def test_parse_playwright_probe_stdout_uses_last_json_line(): assert api._parse_playwright_probe_stdout("noise\n{\"count\": 4}\n") == {"count": 4}
def test_auto_check_team_member_count_returns_minus_one_when_probe_fails(monkeypatch): calls = []
def fake_probe(*_args, **_kwargs): calls.append(True) raise TimeoutError("probe timeout")
monkeypatch.setattr(api, "_run_playwright_probe", fake_probe)
assert api._auto_check_team_member_count(timeout_seconds=0.01, retries=2) == -1 assert len(calls) == 2
def test_auto_check_team_member_count_reads_probe_count(monkeypatch): monkeypatch.setattr(api, "_run_playwright_probe", lambda *_args, **_kwargs: {"count": "5"})
assert api._auto_check_team_member_count(timeout_seconds=0.01, retries=1) == 5123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174from autoteam import chatgpt_api, codex_auth, config
class _FakeTransport: name = "curl_cffi"
def __init__(self, responder): self._responder = responder self.calls = [] self.closed = False
def request(self, method, path, *, headers=None, body=None): call = { "method": method, "path": path, "headers": headers or {}, "body": body, } self.calls.append(call) return self._responder(call, len(self.calls))
def close(self): self.closed = True
def test_chatgpt_api_transport_defaults_to_auto(monkeypatch): monkeypatch.delenv("CHATGPT_API_TRANSPORT", raising=False)
assert config.get_chatgpt_api_transport() == "auto"
def test_start_with_session_prefers_curl_cffi_transport(monkeypatch): transport = _FakeTransport( lambda call, _idx: ( {"status": 200, "body": '{"accessToken":"tok-1"}'} if call["path"] == "/api/auth/session" else {"status": 200, "body": '{"workspace_name":"Idapro"}'} ) ) updates = []
monkeypatch.setattr(chatgpt_api, "build_chatgpt_transport", lambda **_kwargs: transport) monkeypatch.setattr(chatgpt_api, "update_admin_state", lambda **kwargs: updates.append(kwargs))
client = chatgpt_api.ChatGPTTeamAPI() monkeypatch.setattr( client, "_start_browser_session", lambda _session_token: (_ for _ in ()).throw(AssertionError()) )
client.start_with_session("session-1", "acc-1")
assert client.http_transport is transport assert client.browser is None assert client.access_token == "tok-1" assert client.workspace_name == "Idapro" assert updates[-1]["workspace_name"] == "Idapro"
def test_start_with_session_require_browser_skips_curl_cffi(monkeypatch): browser_sessions = []
monkeypatch.setattr( chatgpt_api, "build_chatgpt_transport", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("should not build curl_cffi transport")), )
client = chatgpt_api.ChatGPTTeamAPI() monkeypatch.setattr(client, "_start_browser_session", lambda session_token: browser_sessions.append(session_token))
client.start_with_session("session-2", "acc-2", require_browser=True)
assert browser_sessions == ["session-2"]
def test_session_codex_auth_flow_requires_browser_context(monkeypatch): start_calls = []
class _FakePage: def goto(self, *_args, **_kwargs): return None
class _FakeContext: def new_page(self): return _FakePage()
class _FakeChatGPTTeamAPI: def __init__(self): self.context = _FakeContext()
def start_with_session(self, *args, **kwargs): start_calls.append({"args": args, "kwargs": kwargs})
monkeypatch.setattr(chatgpt_api, "ChatGPTTeamAPI", _FakeChatGPTTeamAPI) monkeypatch.setattr(codex_auth.SessionCodexAuthFlow, "_attach_callback_listeners", lambda self: None) monkeypatch.setattr(codex_auth.SessionCodexAuthFlow, "_inject_auth_cookies", lambda self: None) monkeypatch.setattr(codex_auth.SessionCodexAuthFlow, "_advance", lambda self: {"step": "completed"}) monkeypatch.setattr(codex_auth.time, "sleep", lambda _seconds: None)
flow = codex_auth.SessionCodexAuthFlow( email="admin@example.com", session_token="session-token", account_id="account-id", workspace_name="workspace", password="", auth_file_callback=lambda _bundle: "", )
assert flow.start() == {"step": "completed"} assert start_calls == [ { "args": ("session-token", "account-id", "workspace"), "kwargs": {"require_browser": True}, } ]
def test_api_fetch_falls_back_to_browser_when_curl_cffi_returns_html(monkeypatch): transport = _FakeTransport(lambda _call, _idx: {"status": 200, "body": "<!doctype html><html>challenge</html>"}) ensured = []
client = chatgpt_api.ChatGPTTeamAPI() client.session_token = "session-3" client.account_id = "acc-3" client.http_transport = transport monkeypatch.setattr(client, "_ensure_browser_session", lambda: ensured.append(True)) monkeypatch.setattr( client, "_browser_api_fetch", lambda method, path, body=None: {"status": 200, "body": '{"ok":true}'} )
result = client._api_fetch("GET", "/backend-api/accounts/acc-3/users")
assert ensured == [True] assert result == {"status": 200, "body": '{"ok":true}'}
def test_direct_api_fetch_refreshes_access_token_before_retry(monkeypatch): def responder(call, idx): if idx == 1: return {"status": 401, "body": '{"detail":{"message":"Unauthorized - Access token is missing"}}'} if call["path"] == "/api/auth/session": return {"status": 200, "body": '{"accessToken":"tok-2"}'} return {"status": 200, "body": '{"items":[]}'}
transport = _FakeTransport(responder)
client = chatgpt_api.ChatGPTTeamAPI() client.account_id = "acc-4" client.session_token = "session-4" client.http_transport = transport monkeypatch.setattr(client, "_ensure_browser_session", lambda: (_ for _ in ()).throw(AssertionError()))
result = client._api_fetch("GET", "/backend-api/accounts/acc-4/users")
assert client.access_token == "tok-2" assert result == {"status": 200, "body": '{"items":[]}'} assert [call["path"] for call in transport.calls] == [ "/backend-api/accounts/acc-4/users", "/api/auth/session", "/backend-api/accounts/acc-4/users", ]
def test_stop_closes_curl_cffi_transport(): transport = _FakeTransport(lambda _call, _idx: {"status": 200, "body": "{}"})
client = chatgpt_api.ChatGPTTeamAPI() client.http_transport = transport
client.stop()
assert transport.closed is True assert client.http_transport is None assert client.transport_name is None12345678910111213141516171819202122import pytest
from autoteam import accounts as accounts_modfrom autoteam import api
def test_post_fill_personal_preflight_counts_auth_invalid_as_team_seat(monkeypatch): accounts = [ {"email": "active-1@example.com", "status": accounts_mod.STATUS_ACTIVE}, {"email": "exhausted-1@example.com", "status": accounts_mod.STATUS_EXHAUSTED}, {"email": "auth-invalid-1@example.com", "status": accounts_mod.STATUS_AUTH_INVALID}, {"email": "auth-invalid-2@example.com", "status": accounts_mod.STATUS_AUTH_INVALID}, ]
monkeypatch.setattr(accounts_mod, "load_accounts", lambda: accounts) monkeypatch.setattr(api, "_start_task", lambda *args, **kwargs: pytest.fail("_start_task should not run"))
with pytest.raises(api.HTTPException) as exc: api.post_fill(api.TaskParams(target=1, leave_workspace=True))
assert exc.value.status_code == 409 assert "Team 子号已满 4/4" in str(exc.value.detail)15 unmodified lines1617181920212 unmodified lines2425262728293029 unmodified lines60616263646515 unmodified lines"""from __future__ import annotationsfrom pathlib import Pathfrom unittest.mock import MagicMock2 unmodified linesfrom autoteam import accounts as accounts_modfrom autoteam import manager as manager_modfrom autoteam.account_state import default_machinefrom autoteam.signup_profile import SignupProfile, generate_signup_profile# ---------------------------------------------------------------------------29 unmodified lines# age is non-empty stringassert profile.age and isinstance(profile.age, str)def test_birthday_text_format_for_logs(self):profile = SignupProfile(full_name="Test User",15 unmodified lines16171819202122232 unmodified lines2627282930313233343536373829 unmodified lines6869707172737475767778798015 unmodified lines"""from __future__ import annotationsimport randomfrom datetime import datefrom pathlib import Pathfrom unittest.mock import MagicMock2 unmodified linesfrom autoteam import accounts as accounts_modfrom autoteam import manager as manager_modfrom autoteam.account_state import default_machinefrom autoteam.signup_profile import (MAX_SIGNUP_AGE,MIN_SIGNUP_AGE,SignupProfile,calculate_age,generate_signup_profile,)# ---------------------------------------------------------------------------29 unmodified lines# age is non-empty stringassert profile.age and isinstance(profile.age, str)def test_generate_signup_profile_derives_age_from_birthday(self):today = date(2026, 5, 15)profile = generate_signup_profile(today=today, rng=random.Random(7))assert profile.age == str(calculate_age(profile.birth_date, today))assert MIN_SIGNUP_AGE <= int(profile.age) <= MAX_SIGNUP_AGEdef test_birthday_text_format_for_logs(self):profile = SignupProfile(full_name="Test User",
51 unmodified lines5253545556575859198 unmodified lines258259260261262263264265266267159 unmodified lines42742842943043143243326 unmodified lines46046146246346446546646710 unmodified lines47847948048148248348448548651 unmodified linesproject state.json (which would back-fill an "active" workspace withthe production account_id)."""from autoteam import workspace_pool as wpfrom autoteam import admin_state as asttmp_pool = tmp_path / "workspaces.json"monkeypatch.setattr(wp.default_pool, "_path", tmp_pool, raising=False)198 unmodified linesout1 = mh_mod._apply_master_degraded_classification(workspace_id="acc-a", chatgpt_api=api_stub,)out2 = mh_mod._apply_master_degraded_classification(workspace_id="acc-a", chatgpt_api=api_stub,)out3 = mh_mod._apply_master_degraded_classification(workspace_id="acc-a", chatgpt_api=api_stub,)159 unmodified linesdef test_create_account_direct_accepts_path_rotator(self, monkeypatch):"""create_account_direct(path_rotator=...) 走 rotator 分支,rotator 内部的 action 收到 mail_client 后调用旧路径."""from autoteam.mail.register_dual_path import RegisterPathRotator, RegisterPathExhausted# All strategies raise OTP_TIMEOUT-classified failure to ensure rotator# iterates all strategies → eventually raises RegisterPathExhausted.26 unmodified linesdef test_rotator_classify_failure_triggers_provider_switch(self):"""OTP_TIMEOUT 命中 → should_rotate_on=True → 切下一 provider."""from autoteam.mail.register_dual_path import (classify_register_failure,RegisterFailureType,should_rotate_on,)10 unmodified lines"""acc.mail_provider="addy_io" → _resolve_provider_factory 被调."""from autoteam import mail as mail_pkg# Track resolver callsresolved: list[str] = []original = getattr(mail_pkg, "_resolve_provider_factory")class _StubClient:def __init__(self):51 unmodified lines5253545556575859198 unmodified lines258259260261262263264265266267159 unmodified lines42742842943043143243326 unmodified lines46046146246346446546646710 unmodified lines47847948048148248348451 unmodified linesproject state.json (which would back-fill an "active" workspace withthe production account_id)."""from autoteam import admin_state as astfrom autoteam import workspace_pool as wptmp_pool = tmp_path / "workspaces.json"monkeypatch.setattr(wp.default_pool, "_path", tmp_pool, raising=False)198 unmodified linesout1 = mh_mod._apply_master_degraded_classification(workspace_id="acc-a", chatgpt_api=api_stub,)mh_mod._apply_master_degraded_classification(workspace_id="acc-a", chatgpt_api=api_stub,)mh_mod._apply_master_degraded_classification(workspace_id="acc-a", chatgpt_api=api_stub,)159 unmodified linesdef test_create_account_direct_accepts_path_rotator(self, monkeypatch):"""create_account_direct(path_rotator=...) 走 rotator 分支,rotator 内部的 action 收到 mail_client 后调用旧路径."""from autoteam.mail.register_dual_path import RegisterPathRotator# All strategies raise OTP_TIMEOUT-classified failure to ensure rotator# iterates all strategies → eventually raises RegisterPathExhausted.26 unmodified linesdef test_rotator_classify_failure_triggers_provider_switch(self):"""OTP_TIMEOUT 命中 → should_rotate_on=True → 切下一 provider."""from autoteam.mail.register_dual_path import (RegisterFailureType,classify_register_failure,should_rotate_on,)10 unmodified lines"""acc.mail_provider="addy_io" → _resolve_provider_factory 被调."""from autoteam import mail as mail_pkgresolved: list[str] = []class _StubClient:def __init__(self):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import logging
from autoteam import runtime_resources
def test_collect_runtime_resource_snapshot_reads_cgroup_and_counts_browser_processes(tmp_path, monkeypatch): status = tmp_path / "status" memory_current = tmp_path / "memory.current" memory_max = tmp_path / "memory.max" pids_current = tmp_path / "pids.current" pids_max = tmp_path / "pids.max"
status.write_text("Name:\tpython\nVmRSS:\t2048 kB\n", encoding="utf-8") memory_current.write_text("1048576\n", encoding="utf-8") memory_max.write_text("2097152\n", encoding="utf-8") pids_current.write_text("12\n", encoding="utf-8") pids_max.write_text("768\n", encoding="utf-8")
monkeypatch.setattr(runtime_resources, "PROC_SELF_STATUS", status) monkeypatch.setattr(runtime_resources, "CGROUP_MEMORY_CURRENT", memory_current) monkeypatch.setattr(runtime_resources, "CGROUP_MEMORY_MAX", memory_max) monkeypatch.setattr(runtime_resources, "CGROUP_PIDS_CURRENT", pids_current) monkeypatch.setattr(runtime_resources, "CGROUP_PIDS_MAX", pids_max) monkeypatch.setattr( runtime_resources, "_process_rows", lambda: [ "Z chrome [chrome] <defunct>", "S chrome --type=renderer", "S python -m autoteam", "S playwright driver", ], )
snapshot = runtime_resources.collect_runtime_resource_snapshot()
assert snapshot["rss_mb"] == 2.0 assert snapshot["cgroup_memory_mb"] == 1.0 assert snapshot["cgroup_memory_limit_mb"] == 2.0 assert snapshot["cgroup_memory_usage_ratio"] == 0.5 assert snapshot["pids_current"] == 12 assert snapshot["pids_max"] == 768 assert snapshot["browser_process_total"] == 3 assert snapshot["browser_process_live"] == 2 assert snapshot["browser_process_zombie"] == 1
def test_collect_runtime_resource_snapshot_gracefully_handles_missing_files(tmp_path, monkeypatch): missing = tmp_path / "missing"
monkeypatch.setattr(runtime_resources, "PROC_SELF_STATUS", missing) monkeypatch.setattr(runtime_resources, "CGROUP_MEMORY_CURRENT", missing) monkeypatch.setattr(runtime_resources, "CGROUP_MEMORY_MAX", missing) monkeypatch.setattr(runtime_resources, "CGROUP_PIDS_CURRENT", missing) monkeypatch.setattr(runtime_resources, "CGROUP_PIDS_MAX", missing) monkeypatch.setattr(runtime_resources, "_process_rows", lambda: [])
snapshot = runtime_resources.collect_runtime_resource_snapshot()
assert snapshot["rss_mb"] is None assert snapshot["cgroup_memory_mb"] is None assert snapshot["cgroup_memory_limit_mb"] is None assert snapshot["cgroup_memory_usage_ratio"] is None assert snapshot["pids_current"] is None assert snapshot["pids_max"] is None assert snapshot["browser_process_total"] == 0 assert snapshot["browser_process_live"] == 0 assert snapshot["browser_process_zombie"] == 0
def test_log_runtime_resource_snapshot_warns_and_runs_gc(monkeypatch, caplog): collected = []
monkeypatch.setenv("AUTOTEAM_MEMORY_WARN_RATIO", "0.80") monkeypatch.setenv("AUTOTEAM_ZOMBIE_WARN_THRESHOLD", "1") monkeypatch.setattr(runtime_resources.gc, "collect", lambda: collected.append(True) or 7) monkeypatch.setattr( runtime_resources, "collect_runtime_resource_snapshot", lambda: { "rss_mb": 100.0, "cgroup_memory_mb": 900.0, "cgroup_memory_limit_mb": 1000.0, "cgroup_memory_usage_ratio": 0.9, "pids_current": 50, "pids_max": 768, "browser_process_total": 3, "browser_process_live": 2, "browser_process_zombie": 1, }, )
logger = logging.getLogger("test_runtime_resources") with caplog.at_level(logging.WARNING): snapshot = runtime_resources.log_runtime_resource_snapshot(logger, label="unit")
assert snapshot["cgroup_memory_usage_ratio"] == 0.9 assert collected == [True] assert "gc.collect reclaimed 7 objects" in caplog.text assert "browser zombie processes=1" in caplog.text38 unmodified lines39404142434411 unmodified lines56575859606118 unmodified lines808182838485129 unmodified lines215216217218219220277 unmodified lines49849950050150250338 unmodified linesversion = "0.1.0"source = { editable = "." }dependencies = [{ name = "fastapi" },{ name = "playwright" },{ name = "requests" },11 unmodified lines[package.metadata]requires-dist = [{ name = "fastapi", specifier = ">=0.135.3" },{ name = "playwright", specifier = ">=1.40.0" },{ name = "requests", specifier = ">=2.28.0" },18 unmodified lines{ url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" },][[package]]name = "cfgv"version = "3.5.0"129 unmodified lines{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },][[package]]name = "distlib"version = "0.4.0"277 unmodified lines{ url = "https://files.pythonhosted.org/packages/5d/19/fd3ef348460c80af7bb4669ea7926651d1f95c23ff2df18b9d24bab4f3fa/pre_commit-4.5.1-py2.py3-none-any.whl", hash = "sha256:3b3afd891e97337708c1674210f8eba659b52a38ea5f822ff142d10786221f77", size = 226437, upload-time = "2025-12-16T21:14:32.409Z" },][[package]]name = "pydantic"version = "2.12.5"38 unmodified lines3940414243444511 unmodified lines5758596061626318 unmodified lines828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169129 unmodified lines299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337277 unmodified lines61561661761861962062162262362462562662762862938 unmodified linesversion = "0.1.0"source = { editable = "." }dependencies = [{ name = "curl-cffi" },{ name = "fastapi" },{ name = "playwright" },{ name = "requests" },11 unmodified lines[package.metadata]requires-dist = [{ name = "curl-cffi", specifier = ">=0.13.0" },{ name = "fastapi", specifier = ">=0.135.3" },{ name = "playwright", specifier = ">=1.40.0" },{ name = "requests", specifier = ">=2.28.0" },18 unmodified lines{ url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" },][[package]]name = "cffi"version = "2.0.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pycparser", marker = "implementation_name != 'PyPy'" },]sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/93/d7/516d984057745a6cd96575eea814fe1edd6646ee6efd552fb7b0921dec83/cffi-2.0.0-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:0cf2d91ecc3fcc0625c2c530fe004f82c110405f101548512cce44322fa8ac44", size = 184283, upload-time = "2025-09-08T23:22:08.01Z" },{ url = "https://files.pythonhosted.org/packages/9e/84/ad6a0b408daa859246f57c03efd28e5dd1b33c21737c2db84cae8c237aa5/cffi-2.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f73b96c41e3b2adedc34a7356e64c8eb96e03a3782b535e043a986276ce12a49", size = 180504, upload-time = "2025-09-08T23:22:10.637Z" },{ url = "https://files.pythonhosted.org/packages/50/bd/b1a6362b80628111e6653c961f987faa55262b4002fcec42308cad1db680/cffi-2.0.0-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:53f77cbe57044e88bbd5ed26ac1d0514d2acf0591dd6bb02a3ae37f76811b80c", size = 208811, upload-time = "2025-09-08T23:22:12.267Z" },{ url = "https://files.pythonhosted.org/packages/4f/27/6933a8b2562d7bd1fb595074cf99cc81fc3789f6a6c05cdabb46284a3188/cffi-2.0.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3e837e369566884707ddaf85fc1744b47575005c0a229de3327f8f9a20f4efeb", size = 216402, upload-time = "2025-09-08T23:22:13.455Z" },{ url = "https://files.pythonhosted.org/packages/05/eb/b86f2a2645b62adcfff53b0dd97e8dfafb5c8aa864bd0d9a2c2049a0d551/cffi-2.0.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:5eda85d6d1879e692d546a078b44251cdd08dd1cfb98dfb77b670c97cee49ea0", size = 203217, upload-time = "2025-09-08T23:22:14.596Z" },{ url = "https://files.pythonhosted.org/packages/9f/e0/6cbe77a53acf5acc7c08cc186c9928864bd7c005f9efd0d126884858a5fe/cffi-2.0.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9332088d75dc3241c702d852d4671613136d90fa6881da7d770a483fd05248b4", size = 203079, upload-time = "2025-09-08T23:22:15.769Z" },{ url = "https://files.pythonhosted.org/packages/98/29/9b366e70e243eb3d14a5cb488dfd3a0b6b2f1fb001a203f653b93ccfac88/cffi-2.0.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fc7de24befaeae77ba923797c7c87834c73648a05a4bde34b3b7e5588973a453", size = 216475, upload-time = "2025-09-08T23:22:17.427Z" },{ url = "https://files.pythonhosted.org/packages/21/7a/13b24e70d2f90a322f2900c5d8e1f14fa7e2a6b3332b7309ba7b2ba51a5a/cffi-2.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:cf364028c016c03078a23b503f02058f1814320a56ad535686f90565636a9495", size = 218829, upload-time = "2025-09-08T23:22:19.069Z" },{ url = "https://files.pythonhosted.org/packages/60/99/c9dc110974c59cc981b1f5b66e1d8af8af764e00f0293266824d9c4254bc/cffi-2.0.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e11e82b744887154b182fd3e7e8512418446501191994dbf9c9fc1f32cc8efd5", size = 211211, upload-time = "2025-09-08T23:22:20.588Z" },{ url = "https://files.pythonhosted.org/packages/49/72/ff2d12dbf21aca1b32a40ed792ee6b40f6dc3a9cf1644bd7ef6e95e0ac5e/cffi-2.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8ea985900c5c95ce9db1745f7933eeef5d314f0565b27625d9a10ec9881e1bfb", size = 218036, upload-time = "2025-09-08T23:22:22.143Z" },{ url = "https://files.pythonhosted.org/packages/e2/cc/027d7fb82e58c48ea717149b03bcadcbdc293553edb283af792bd4bcbb3f/cffi-2.0.0-cp310-cp310-win32.whl", hash = "sha256:1f72fb8906754ac8a2cc3f9f5aaa298070652a0ffae577e0ea9bd480dc3c931a", size = 172184, upload-time = "2025-09-08T23:22:23.328Z" },{ url = "https://files.pythonhosted.org/packages/33/fa/072dd15ae27fbb4e06b437eb6e944e75b068deb09e2a2826039e49ee2045/cffi-2.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:b18a3ed7d5b3bd8d9ef7a8cb226502c6bf8308df1525e1cc676c3680e7176739", size = 182790, upload-time = "2025-09-08T23:22:24.752Z" },{ url = "https://files.pythonhosted.org/packages/12/4a/3dfd5f7850cbf0d06dc84ba9aa00db766b52ca38d8b86e3a38314d52498c/cffi-2.0.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe", size = 184344, upload-time = "2025-09-08T23:22:26.456Z" },{ url = "https://files.pythonhosted.org/packages/4f/8b/f0e4c441227ba756aafbe78f117485b25bb26b1c059d01f137fa6d14896b/cffi-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c", size = 180560, upload-time = "2025-09-08T23:22:28.197Z" },{ url = "https://files.pythonhosted.org/packages/b1/b7/1200d354378ef52ec227395d95c2576330fd22a869f7a70e88e1447eb234/cffi-2.0.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92", size = 209613, upload-time = "2025-09-08T23:22:29.475Z" },{ url = "https://files.pythonhosted.org/packages/b8/56/6033f5e86e8cc9bb629f0077ba71679508bdf54a9a5e112a3c0b91870332/cffi-2.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93", size = 216476, upload-time = "2025-09-08T23:22:31.063Z" },{ url = "https://files.pythonhosted.org/packages/dc/7f/55fecd70f7ece178db2f26128ec41430d8720f2d12ca97bf8f0a628207d5/cffi-2.0.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5", size = 203374, upload-time = "2025-09-08T23:22:32.507Z" },{ url = "https://files.pythonhosted.org/packages/84/ef/a7b77c8bdc0f77adc3b46888f1ad54be8f3b7821697a7b89126e829e676a/cffi-2.0.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664", size = 202597, upload-time = "2025-09-08T23:22:34.132Z" },{ url = "https://files.pythonhosted.org/packages/d7/91/500d892b2bf36529a75b77958edfcd5ad8e2ce4064ce2ecfeab2125d72d1/cffi-2.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26", size = 215574, upload-time = "2025-09-08T23:22:35.443Z" },{ url = "https://files.pythonhosted.org/packages/44/64/58f6255b62b101093d5df22dcb752596066c7e89dd725e0afaed242a61be/cffi-2.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9", size = 218971, upload-time = "2025-09-08T23:22:36.805Z" },{ url = "https://files.pythonhosted.org/packages/ab/49/fa72cebe2fd8a55fbe14956f9970fe8eb1ac59e5df042f603ef7c8ba0adc/cffi-2.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414", size = 211972, upload-time = "2025-09-08T23:22:38.436Z" },{ url = "https://files.pythonhosted.org/packages/0b/28/dd0967a76aab36731b6ebfe64dec4e981aff7e0608f60c2d46b46982607d/cffi-2.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743", size = 217078, upload-time = "2025-09-08T23:22:39.776Z" },{ url = "https://files.pythonhosted.org/packages/2b/c0/015b25184413d7ab0a410775fdb4a50fca20f5589b5dab1dbbfa3baad8ce/cffi-2.0.0-cp311-cp311-win32.whl", hash = "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", size = 172076, upload-time = "2025-09-08T23:22:40.95Z" },{ url = "https://files.pythonhosted.org/packages/ae/8f/dc5531155e7070361eb1b7e4c1a9d896d0cb21c49f807a6c03fd63fc877e/cffi-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", size = 182820, upload-time = "2025-09-08T23:22:42.463Z" },{ url = "https://files.pythonhosted.org/packages/95/5c/1b493356429f9aecfd56bc171285a4c4ac8697f76e9bbbbb105e537853a1/cffi-2.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", size = 177635, upload-time = "2025-09-08T23:22:43.623Z" },{ url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" },{ url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" },{ url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" },{ url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" },{ url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" },{ url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" },{ url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" },{ url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" },{ url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" },{ url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" },{ url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" },{ url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" },{ url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230, upload-time = "2025-09-08T23:23:00.879Z" },{ url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043, upload-time = "2025-09-08T23:23:02.231Z" },{ url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446, upload-time = "2025-09-08T23:23:03.472Z" },{ url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101, upload-time = "2025-09-08T23:23:04.792Z" },{ url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948, upload-time = "2025-09-08T23:23:06.127Z" },{ url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422, upload-time = "2025-09-08T23:23:07.753Z" },{ url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499, upload-time = "2025-09-08T23:23:09.648Z" },{ url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928, upload-time = "2025-09-08T23:23:10.928Z" },{ url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302, upload-time = "2025-09-08T23:23:12.42Z" },{ url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" },{ url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" },{ url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" },{ url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320, upload-time = "2025-09-08T23:23:18.087Z" },{ url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487, upload-time = "2025-09-08T23:23:19.622Z" },{ url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049, upload-time = "2025-09-08T23:23:20.853Z" },{ url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793, upload-time = "2025-09-08T23:23:22.08Z" },{ url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300, upload-time = "2025-09-08T23:23:23.314Z" },{ url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244, upload-time = "2025-09-08T23:23:24.541Z" },{ url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828, upload-time = "2025-09-08T23:23:26.143Z" },{ url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926, upload-time = "2025-09-08T23:23:27.873Z" },{ url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" },{ url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" },{ url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" },{ url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773, upload-time = "2025-09-08T23:23:29.347Z" },{ url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013, upload-time = "2025-09-08T23:23:30.63Z" },{ url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593, upload-time = "2025-09-08T23:23:31.91Z" },{ url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354, upload-time = "2025-09-08T23:23:33.214Z" },{ url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480, upload-time = "2025-09-08T23:23:34.495Z" },{ url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584, upload-time = "2025-09-08T23:23:36.096Z" },{ url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443, upload-time = "2025-09-08T23:23:37.328Z" },{ url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437, upload-time = "2025-09-08T23:23:38.945Z" },{ url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" },{ url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" },{ url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" },][[package]]name = "cfgv"version = "3.5.0"129 unmodified lines{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },][[package]]name = "curl-cffi"version = "0.15.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "certifi" },{ name = "cffi" },{ name = "rich" },]sdist = { url = "https://files.pythonhosted.org/packages/48/5b/89fcfebd3e5e85134147ac99e9f2b2271165fd4d71984fc65da5f17819b7/curl_cffi-0.15.0.tar.gz", hash = "sha256:ea0c67652bf6893d34ee0f82c944f37e488f6147e9421bef1771cc6545b02ded", size = 196437, upload-time = "2026-04-03T11:12:31.525Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/5e/42/54ddd442c795f30ce5dd4e49f87ce77505958d3777cd96a91567a3975d2a/curl_cffi-0.15.0-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:bda66404010e9ed743b1b83c20c86f24fe21a9a6873e17479d6e67e29d8ded28", size = 2795267, upload-time = "2026-04-03T11:11:46.48Z" },{ url = "https://files.pythonhosted.org/packages/83/2d/3915e238579b3c5a92cead5c79130c3b8d20caaba7616cc4d894650e1d6b/curl_cffi-0.15.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:a25620d9bf989c9c029a7d1642999c4c265abb0bad811deb2f77b0b5b2b12e5b", size = 2573544, upload-time = "2026-04-03T11:11:47.951Z" },{ url = "https://files.pythonhosted.org/packages/2a/b3/9d2f1057749a1b07ba1989db3c1503ce8bed998310bae9aea2c43aa64f20/curl_cffi-0.15.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:582e570aa2586b96ed47cf4a17586b9a3c462cbe43f780487c3dc245c6ef1527", size = 10515369, upload-time = "2026-04-03T11:11:50.126Z" },{ url = "https://files.pythonhosted.org/packages/b5/1d/6d10dded5ce3fd8157e558ebd97d09e551b77a62cdc1c31e93d0a633cee5/curl_cffi-0.15.0-cp310-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:838e48212447d9c81364b04707a5c861daf08f8320f9ecb3406a8919d1d5c3b3", size = 10160045, upload-time = "2026-04-03T11:11:52.664Z" },{ url = "https://files.pythonhosted.org/packages/5c/12/c70b835487ace3b9ba1502631912e3440082b8ae3a162f60b59cb0b6444d/curl_cffi-0.15.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b6c847d86283b07ae69bb72c82eb8a59242277142aa35b89850f89e792a02fc", size = 11090433, upload-time = "2026-04-03T11:11:55.049Z" },{ url = "https://files.pythonhosted.org/packages/ea/0d/78edcc4f71934225db99df68197a107386d59080742fc7bf6bb4d007924f/curl_cffi-0.15.0-cp310-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:9e5e69eee735f659287e2c84444319d68a1fa68dd37abf228943a4074864283a", size = 10479178, upload-time = "2026-04-03T11:11:57.685Z" },{ url = "https://files.pythonhosted.org/packages/5b/84/1e101c1acb1ea2f0b4992f5c3024f596d8e21db0d53540b9d583f673c4e7/curl_cffi-0.15.0-cp310-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa1323950224db24f4c510d010b3affa02196ca853fb424191fa917a513d3f4b", size = 10317051, upload-time = "2026-04-03T11:12:00.295Z" },{ url = "https://files.pythonhosted.org/packages/28/42/8ef236b22a6c23d096c85a1dc507efe37bfdfc7a2f8a4b34efb590197369/curl_cffi-0.15.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:41f80170ba844009273b2660da1964ec31e99e5719d16b3422ada87177e32e13", size = 11299660, upload-time = "2026-04-03T11:12:02.791Z" },{ url = "https://files.pythonhosted.org/packages/1d/01/56aeb055d962da87a1be0d74c6c644e251c7e88129b5471dc44ac724e678/curl_cffi-0.15.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1977e1e12cfb5c11352cbb74acef1bed24eb7d226dab61ca57c168c21acd4d61", size = 11945049, upload-time = "2026-04-03T11:12:05.912Z" },{ url = "https://files.pythonhosted.org/packages/d8/8c/2abf99a38d6340d66cf0557e0c750ef3f8883dfc5d450087e01c85861343/curl_cffi-0.15.0-cp310-abi3-win_amd64.whl", hash = "sha256:5a0c1896a0d5a5ac1eb89cd24b008d2b718dd1df6fd2f75451b59ca66e49e572", size = 1661649, upload-time = "2026-04-03T11:12:07.948Z" },{ url = "https://files.pythonhosted.org/packages/3d/39/dfd54f2240d3a9b96d77bacc62b97813b35e2aa8ecf5cd5013c683f1ba96/curl_cffi-0.15.0-cp310-abi3-win_arm64.whl", hash = "sha256:a6d57f8389273a3a1f94370473c74897467bcc36af0a17336989780c507fa43d", size = 1410741, upload-time = "2026-04-03T11:12:10.073Z" },{ url = "https://files.pythonhosted.org/packages/19/6a/c24df8a4fc22fa84070dcd94abeba43c15e08cc09e35869565c0bad196fd/curl_cffi-0.15.0-cp313-abi3-android_24_arm64_v8a.whl", hash = "sha256:4682dc38d4336e0eb0b185374db90a760efde63cbea994b4e63f3521d44c4c92", size = 7190427, upload-time = "2026-04-03T11:12:12.142Z" },{ url = "https://files.pythonhosted.org/packages/11/56/132225cb3491d07cc6adcce5fe395e059bde87c68cff1ef87a31c88c7819/curl_cffi-0.15.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:967ad7355bd8e9586f8c2d02eaa99953747549e7ea4a9b25cd53353e6b67fe6d", size = 2795723, upload-time = "2026-04-03T11:12:13.668Z" },{ url = "https://files.pythonhosted.org/packages/07/8f/f4f83cd303bef7e8f1749512e5dd157e7e5d08b0a36c8211f9640a2757bf/curl_cffi-0.15.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7e63539d0d839d0a8c5eacf86229bc68c57803547f35e0db7ee0986328b478c3", size = 2573739, upload-time = "2026-04-03T11:12:15.08Z" },{ url = "https://files.pythonhosted.org/packages/e8/5c/643d65c7fc9acd742876aa55c2d7823c438cb7665810acd2e66c9976c4d9/curl_cffi-0.15.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:08c799b89740b9bc49c09fbc3d5907f13ac1f845ca52620507ef9466d4639dd5", size = 10521046, upload-time = "2026-04-03T11:12:17.034Z" },{ url = "https://files.pythonhosted.org/packages/7f/0b/9b8037113c93f4c5323096163471fa7c35c7676c3f608eeaf1287cd99d58/curl_cffi-0.15.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7b7a92767a888ee90147e18964b396d8435ff42737030d6fb00824ffd6094805", size = 11096115, upload-time = "2026-04-03T11:12:19.694Z" },{ url = "https://files.pythonhosted.org/packages/5f/96/fff2fcbd924ef4042e0d67379f751a8a4e3186a91e75e35a4cf218b306ee/curl_cffi-0.15.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:829cc357061ecb99cc2d406301f609a039e05665322f5c025ec67c38b0dc49ce", size = 11305346, upload-time = "2026-04-03T11:12:22.151Z" },{ url = "https://files.pythonhosted.org/packages/53/1b/304b253a45ab28691c8c5e8cca1e6cbb9cf8e46dfceae4648dd536f75e73/curl_cffi-0.15.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:408d6f14e346841cd889c2e0962832bb235ba3b6749ebf609f347f747da5e60f", size = 11949834, upload-time = "2026-04-03T11:12:24.986Z" },{ url = "https://files.pythonhosted.org/packages/5a/ff/4723d92f08259c707a974aba27a08d0a822b9555e35ca581bf18d055a364/curl_cffi-0.15.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b624c7ce087bfda967a013ed0a64702a525444e5b6e97d23534d567ccc6525aa", size = 1702771, upload-time = "2026-04-03T11:12:28.201Z" },{ url = "https://files.pythonhosted.org/packages/59/8c/36bbe06d66fa2b765e4a07199f643a59a9cd1a754207a96335402a9520f4/curl_cffi-0.15.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0b6c0543b993996670e9e4b78e305a2d60809d5681903ffb5568e21a387434d3", size = 1466312, upload-time = "2026-04-03T11:12:30.054Z" },][[package]]name = "distlib"version = "0.4.0"277 unmodified lines{ url = "https://files.pythonhosted.org/packages/5d/19/fd3ef348460c80af7bb4669ea7926651d1f95c23ff2df18b9d24bab4f3fa/pre_commit-4.5.1-py2.py3-none-any.whl", hash = "sha256:3b3afd891e97337708c1674210f8eba659b52a38ea5f822ff142d10786221f77", size = 226437, upload-time = "2025-12-16T21:14:32.409Z" },][[package]]name = "pycparser"version = "3.0"source = { registry = "https://pypi.org/simple" }sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" },][[package]]name = "pydantic"version = "2.12.5"
.env.example+8
.trellis/spec/backend/database-guidelines.mdAdded+51
.trellis/spec/backend/directory-structure.mdAdded+54
.trellis/spec/backend/error-handling.mdAdded+51
.trellis/spec/backend/free-registration-hardening.mdAdded+88
.trellis/spec/backend/index.mdAdded+40
.trellis/spec/backend/logging-guidelines.mdAdded+51
.trellis/spec/backend/quality-guidelines.mdAdded+51
.trellis/spec/backend/runtime-docker-hardening.mdAdded+104
.trellis/spec/guides/code-reuse-thinking-guide.mdAdded+105
.trellis/spec/guides/cross-layer-thinking-guide.mdAdded+94
.trellis/spec/guides/index.mdAdded+79
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/check.jsonlAdded+30
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/completion-audit-2026-05-15.mdAdded+53
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/free-registration-round2-completion-audit.mdAdded+37
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/implement.jsonlAdded+14
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/prd.mdAdded+62
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/research/docker-playwright-hardening.mdAdded+24
.trellis/tasks/05-15-autoteam1-hardening-docker-apply/task.jsonAdded+26
Dockerfile.fastAdded+29
docker-compose.yml+15
docker-entrypoint.sh+16-9
docs/docker.md+51-1
prompts/0515/autoteam1-absorption-audit.mdAdded+59
prompts/0515/free-registration-round2-critical-audit.mdAdded+112
prompts/0515/implementation-plan.mdAdded+113
prompts/0515/prd.mdAdded+122
prompts/0515/research-docker-playwright-hardening.mdAdded+52
prompts/0515/spec.mdAdded+142
pyproject.toml+1
src/autoteam/api.py+137-9
src/autoteam/chatgpt_api.py+255-56
src/autoteam/chatgpt_transport.pyAdded+99
src/autoteam/codex_auth.py+6-1
src/autoteam/config.py+56-1
src/autoteam/manager.py+31-31
src/autoteam/playwright_lifecycle.pyAdded+38
src/autoteam/playwright_probe.pyAdded+45
src/autoteam/runtime_resources.pyAdded+182
src/autoteam/signup_profile.py+67-7
tests/integration/test_docker_guard.py+62
tests/unit/test_api_playwright_cleanup.pyAdded+155
tests/unit/test_chatgpt_transport.pyAdded+174
tests/unit/test_free_registration_hardening.pyAdded+22
tests/unit/test_round12_s3_cherry_pick.py+16-1
tests/unit/test_round12_wireup.py+5-7
tests/unit/test_runtime_resources.pyAdded+100
uv.lock+126