diff --git a/.dockerignore b/.dockerignore index 4cc64d782821148aba1376b99595bd11c9836d5a..39ba0167755012ab8882a7646f497e111e7fb4ac 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,17 +1,69 @@ -.git -.gitignore -.agents -.codex -.trellis -.env -.env.* -target -.local-postgres -run-output -run-logs -linuxdo-auth-store.json -monitor -AUDIT.md -AGENTS.md -Dockerfile* -README.md +# Git 相关 +.git +.github +.gitignore + +# 环境配置 +.env +.env.local +.env.*.local +.venv +venv +env/ + +# Python 缓存 +__pycache__/ +**/__pycache__/ +**/*.pyc +**/*.pyo +**/*.pyd +.Python +*.so +*.egg +*.egg-info/ +dist/ +build/ +.pytest_cache/ +.coverage +htmlcov/ + +# 日志和数据 +*.log +data/ +logs/ +outputs/ +temp/ +tmp/ + +# 前端 +frontend/node_modules/ +frontend/dist/ +frontend/.vite/ +frontend/.turbo/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# 文档(构建时不需要) +*.md +!README.md +SESSION_*.md +FIX_*.md +QUICK_*.md +START_*.md +TOOL_*.md + +# 测试文件 +tests/ +test_*.py +*_test.py + +# 其他 +.dockerignore +Dockerfile* +docker-compose*.yml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..d267519475ad76001b664951f0808dd0400c5456 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,6 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +charset = utf-8 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..c1948a84135191bb9f5e47e60e231bb6e57c79c2 --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +ADMIN_KEY=change-me-now +PORT=7860 +WORKERS=1 +LOG_LEVEL=INFO +MAX_INFLIGHT=2 +MAX_RETRIES=3 +ACCOUNT_MIN_INTERVAL_MS=0 +REQUEST_JITTER_MIN_MS=0 +REQUEST_JITTER_MAX_MS=0 +RATE_LIMIT_BASE_COOLDOWN=600 +RATE_LIMIT_MAX_COOLDOWN=3600 +ACCOUNTS_FILE=/workspace/data/accounts.json +USERS_FILE=/workspace/data/users.json +CAPTURES_FILE=/workspace/data/captures.json +CONTEXT_GENERATED_DIR=/workspace/data/context_files +CONTEXT_CACHE_FILE=/workspace/data/context_cache.json +UPLOADED_FILES_FILE=/workspace/data/uploaded_files.json +CONTEXT_AFFINITY_FILE=/workspace/data/session_affinity.json +CONTEXT_INLINE_MAX_CHARS=4000 +CONTEXT_FORCE_FILE_MAX_CHARS=10000 +CONTEXT_ATTACHMENT_TTL_SECONDS=1800 +CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS=60 diff --git a/.hfignore b/.hfignore deleted file mode 100644 index 1d5dbd13de552bd7d98ab0b981d82507a81d44d6..0000000000000000000000000000000000000000 --- a/.hfignore +++ /dev/null @@ -1,14 +0,0 @@ -.git/ -.agents/ -.codex/ -.trellis/ -.env -.env.* -target/ -.local-postgres/ -run-output/ -run-logs/ -linuxdo-auth-store.json -monitor/ -AUDIT.md -AGENTS.md diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index f0e2426dbe473c604798cf1a4b7cd023f808fd83..0000000000000000000000000000000000000000 --- a/Cargo.lock +++ /dev/null @@ -1,2410 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "atoi" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" -dependencies = [ - "num-traits", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "axum" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" -dependencies = [ - "axum-core", - "bytes", - "form_urlencoded", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-util", - "itoa", - "matchit", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "serde_core", - "serde_json", - "serde_path_to_error", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "axum-core" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "mime", - "pin-project-lite", - "sync_wrapper", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bitflags" -version = "2.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" - -[[package]] -name = "cc" -version = "1.2.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "crc" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" -dependencies = [ - "crc-catalog", -] - -[[package]] -name = "crc-catalog" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" - -[[package]] -name = "crossbeam-queue" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "displaydoc" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "dotenvy" -version = "0.15.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" - -[[package]] -name = "either" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" -dependencies = [ - "serde", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "etcetera" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" -dependencies = [ - "cfg-if", - "home", - "windows-sys 0.48.0", -] - -[[package]] -name = "event-listener" -version = "5.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" -dependencies = [ - "concurrent-queue", - "parking", - "pin-project-lite", -] - -[[package]] -name = "fastrand" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-intrusive" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" -dependencies = [ - "futures-core", - "lock_api", - "parking_lot", -] - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-sink" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 5.3.0", - "wasip2", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", -] - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "hashlink" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" -dependencies = [ - "hashbrown 0.15.5", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "home" -version = "0.5.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "http" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hyper" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "tokio", - "tokio-rustls", - "tower-service", - "webpki-roots 1.0.8", -] - -[[package]] -name = "hyper-util" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" -dependencies = [ - "base64", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ideal-link-extractor-rust" -version = "0.1.0" -dependencies = [ - "async-trait", - "axum", - "base64", - "clap", - "regex", - "reqwest", - "serde", - "serde_json", - "sqlx", - "tempfile", - "thiserror 1.0.69", - "tokio", - "url", - "uuid", -] - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", -] - -[[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "js-sys" -version = "0.3.103" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "libredox" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" -dependencies = [ - "bitflags", - "libc", - "plain", - "redox_syscall 0.9.0", -] - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - -[[package]] -name = "lru-slab" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" - -[[package]] -name = "matchit" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" - -[[package]] -name = "md-5" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" -dependencies = [ - "cfg-if", - "digest", -] - -[[package]] -name = "memchr" -version = "2.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "mio" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall 0.5.18", - "smallvec", - "windows-link", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "plain" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quinn" -version = "0.11.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" -dependencies = [ - "bytes", - "cfg_aliases", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash", - "rustls", - "socket2", - "thiserror 2.0.18", - "tokio", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-proto" -version = "0.11.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" -dependencies = [ - "bytes", - "getrandom 0.3.4", - "lru-slab", - "rand 0.9.4", - "ring", - "rustc-hash", - "rustls", - "rustls-pki-types", - "slab", - "thiserror 2.0.18", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.60.2", -] - -[[package]] -name = "quote" -version = "1.0.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - -[[package]] -name = "redox_syscall" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5102a6aaa05aa011a238e178e6bca86d2cb56fc9f586d37cb80f5bca6e07759" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "reqwest" -version = "0.12.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" -dependencies = [ - "base64", - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots 1.0.8", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustc-hash" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" - -[[package]] -name = "rustix" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" -dependencies = [ - "web-time", - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.150" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_path_to_error" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" -dependencies = [ - "itoa", - "serde", - "serde_core", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" -dependencies = [ - "serde", -] - -[[package]] -name = "socket2" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "sqlx" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" -dependencies = [ - "sqlx-core", - "sqlx-macros", - "sqlx-postgres", -] - -[[package]] -name = "sqlx-core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" -dependencies = [ - "base64", - "bytes", - "crc", - "crossbeam-queue", - "either", - "event-listener", - "futures-core", - "futures-intrusive", - "futures-io", - "futures-util", - "hashbrown 0.15.5", - "hashlink", - "indexmap", - "log", - "memchr", - "once_cell", - "percent-encoding", - "rustls", - "serde", - "serde_json", - "sha2", - "smallvec", - "thiserror 2.0.18", - "tokio", - "tokio-stream", - "tracing", - "url", - "webpki-roots 0.26.11", -] - -[[package]] -name = "sqlx-macros" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" -dependencies = [ - "proc-macro2", - "quote", - "sqlx-core", - "sqlx-macros-core", - "syn", -] - -[[package]] -name = "sqlx-macros-core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" -dependencies = [ - "dotenvy", - "either", - "heck", - "hex", - "once_cell", - "proc-macro2", - "quote", - "serde", - "serde_json", - "sha2", - "sqlx-core", - "sqlx-postgres", - "syn", - "tokio", - "url", -] - -[[package]] -name = "sqlx-postgres" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" -dependencies = [ - "atoi", - "base64", - "bitflags", - "byteorder", - "crc", - "dotenvy", - "etcetera", - "futures-channel", - "futures-core", - "futures-util", - "hex", - "hkdf", - "hmac", - "home", - "itoa", - "log", - "md-5", - "memchr", - "once_cell", - "rand 0.8.6", - "serde", - "serde_json", - "sha2", - "smallvec", - "sqlx-core", - "stringprep", - "thiserror 2.0.18", - "tracing", - "whoami", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "2.0.118" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" -dependencies = [ - "thiserror-impl 2.0.18", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.52.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tower" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" -dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-http" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" -dependencies = [ - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "url", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "serde_core", - "wasm-bindgen", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" - -[[package]] -name = "wasm-bindgen" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "web-sys" -version = "0.3.103" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "0.26.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" -dependencies = [ - "webpki-roots 1.0.8", -] - -[[package]] -name = "webpki-roots" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "whoami" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" -dependencies = [ - "libredox", - "wasite", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "yoke" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.52" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.52" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zmij" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index d75d4cf8ce9619cdd390426733648a75b1d0731e..0000000000000000000000000000000000000000 --- a/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "ideal-link-extractor-rust" -version = "0.1.0" -edition = "2021" - -[features] -# PostgreSQL-backed auth integration tests need an isolated DATABASE_URL and -# are intentionally not part of the hermetic extractor unit-test target. -postgres-integration-tests = [] - -[dependencies] -async-trait = "0.1" -axum = "0.8" -base64 = "0.22" -clap = { version = "4", features = ["derive"] } -regex = "1" -reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "socks"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres"] } -thiserror = "1" -tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } -url = "2" -uuid = { version = "1", features = ["v4", "serde"] } - -[dev-dependencies] -tempfile = "3" diff --git a/Dockerfile b/Dockerfile index 3ec8881e24d4c6eedf8df83dcc9c5cc91a44b5e6..21116462c9ab03777cc96cdbff809a1e8e20c3e0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,78 @@ -FROM rust:1.88-bookworm AS builder - -WORKDIR /build - -COPY Cargo.toml Cargo.lock ./ -COPY src ./src - -RUN cargo build --release --locked - -FROM debian:bookworm-slim AS runtime - -RUN apt-get update \ - && apt-get install --yes --no-install-recommends ca-certificates curl \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /app - -COPY --from=builder /build/target/release/ideal-link-extractor-rust /usr/local/bin/ideal-link-extractor-rust -COPY queue-config.json ./queue-config.json - -EXPOSE 7860 - -HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \ - CMD curl --fail --silent --show-error http://127.0.0.1:7860/api/config > /dev/null || exit 1 - -CMD ["ideal-link-extractor-rust", "serve", "--listen", "0.0.0.0:7860"] +# syntax=docker/dockerfile:1.7 + +# Stage 1: Build frontend assets once on the build platform. +FROM --platform=$BUILDPLATFORM node:20-bookworm-slim AS frontend-builder +WORKDIR /app +COPY frontend/package*.json ./ +RUN npm ci +COPY frontend/ ./ +RUN npm run build + +# Stage 2: Runtime image. +FROM python:3.12-slim-bookworm +WORKDIR /workspace + +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONIOENCODING=utf-8 \ + PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 \ + PORT=7860 \ + WORKERS=1 \ + LOG_LEVEL=INFO \ + PYTHONPATH=/workspace + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + wget \ + libasound2 \ + libatk-bridge2.0-0 \ + libatk1.0-0 \ + libcups2 \ + libdbus-1-3 \ + libdbus-glib-1-2 \ + libdrm2 \ + libgbm1 \ + libglib2.0-0 \ + libgtk-3-0 \ + libnspr4 \ + libnss3 \ + libpangocairo-1.0-0 \ + libpulse0 \ + libx11-6 \ + libx11-xcb1 \ + libxcb1 \ + libxcomposite1 \ + libxdamage1 \ + libxext6 \ + libxfixes3 \ + libxkbcommon0 \ + libxrandr2 \ + libxshmfence1 \ + fonts-liberation \ + fonts-noto-cjk \ + && rm -rf /var/lib/apt/lists/* + +COPY backend/requirements.txt /tmp/requirements.txt +RUN pip install -r /tmp/requirements.txt + +# HF Spaces runs the container as uid 1000; build runtime-writable assets as that user. +RUN useradd -m -u 1000 user && chown user:user /workspace +ENV HOME=/home/user +USER user + +# Download Camoufox browser at build time so runtime hosts do not need to fetch it again. +RUN python -m camoufox fetch + +COPY --chown=user:user backend/ ./backend/ +COPY --chown=user:user start.py ./ +COPY --from=frontend-builder --chown=user:user /app/dist ./frontend/dist +RUN mkdir -p /workspace/data /workspace/logs /workspace/frontend + +EXPOSE 7860 + +HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \ + CMD curl -fsS "http://127.0.0.1:${PORT:-7860}/healthz" || exit 1 + +CMD ["sh", "-c", "python -m uvicorn backend.main:app --host 0.0.0.0 --port ${PORT:-7860} --workers ${WORKERS:-1}"] diff --git a/README.md b/README.md index b6f550f6a29bff3aedeba93b64ae00bfbd7ff2ec..18e48bc0194ae7cbf2505eac4b93ddbb7d874e0a 100644 --- a/README.md +++ b/README.md @@ -1,144 +1,1226 @@ --- -title: iDEAL Link Extractor Rust -emoji: 🔗 +title: opllplus +emoji: "⚡" colorFrom: blue colorTo: indigo sdk: docker -pinned: false app_port: 7860 +pinned: false --- -# iDEAL Link Extractor Rust - -Minimal Rust local browser UI extracted from the Python iDEAL path. - -## Hugging Face Spaces - -This repository can run as a Hugging Face Docker Space. The container listens -on `0.0.0.0:7860` and starts the existing Axum browser service. - -Configure the following Space Secret before starting the container: - -- `DATABASE_URL`: PostgreSQL connection URI. Supabase Session pooler URLs should - include `sslmode=require`. - -Optional Secrets: - -- `OPENAI_PAY_DEFAULT_PROXY`: retained only for legacy/internal compatibility. - Browser extraction reads its required proxy pools from the page instead of - this Secret. -- `LINUXDO_CLIENT_ID`, `LINUXDO_CLIENT_SECRET`, and `LINUXDO_REDIRECT_URI`: only - needed when LinuxDo OAuth is enabled. - -The Space health endpoint is `GET /api/config`. Secrets must be configured in -the Hugging Face Space settings and must not be committed to this repository. - -## Fixed behavior - -For iDEAL: - -- browser `link_type`: `ideal` or `paypal` -- billing country: `NL` -- currency: `EUR` -- checkout UI mode: `custom` -- client fingerprint: `apple-safari` -- Checkout/Stripe/provider/approve route: selected from the submitted Checkout pool -- promotion update route: selected from the submitted Promotion Update pool -- approve attempts: `20` -- approve concurrency: `1` - -PayPal uses a Chrome fingerprint with `US / USD` billing and the route `US Checkout → VN Promotion Update → TR Stripe/provider → US approve/poll`. The three submitted pools rotate independently for up to 10 full Checkout rebuilds. Final approve is attempted once per Checkout with concurrency 1. Checkout creation, Stripe tax-region update, baseline PayPal PaymentMethod, and inline-confirm PaymentMethod data all use the same US billing address/state. - -## Run - -```bash -cargo run -- serve --listen IP_REDACTED:8793 -``` - -Open `http://IP_REDACTED:8793/`. The page no longer requires LinuxDo login: users activate the page by entering a CDK. Existing LinuxDo-bound accounts and their already-bound CDKs continue to work, and LinuxDo OAuth routes remain available for backward compatibility. A use is deducted only after a link is successfully extracted; failed jobs do not reduce the count. - -Production user/session/CDK data is stored in PostgreSQL. `DATABASE_URL` is required; the service fails at startup if it is missing. The server runs idempotent schema migration on startup and does not fall back to the old local JSON store. - -For local deployment, `DATABASE_URL` may be placed in the project `.env` file. A local PostgreSQL data directory can live under `.local-postgres/`, which is ignored by git. - -Direct CLI extraction is not available; extraction is intentionally exposed only through the CDK-gated browser API. - -- `GET /api/oauth/linuxdo/login` to start LinuxDo OAuth login. -- `GET /api/oauth/linuxdo` is the LinuxDo OAuth callback URL. -- `GET /api/auth/me` to read the current LinuxDo user, CDK, and remaining uses. -- `POST /api/auth/logout` to clear the local session. -- `POST /api/cdk/bind` with `{ "cdk" }` to activate a browser session with a CDK when not logged in, or to bind a pre-provisioned CDK after the active CDK is exhausted and no jobs are pending. -- `POST /api/extract` to enqueue a job: - - iDEAL: `{ "access_token", "link_type": "ideal", "checkout_proxy_pool", "promotion_proxy_pool" }`; both pools are required newline-delimited strings. - - PayPal: `{ "access_token", "link_type": "paypal", "paypal_checkout_proxy_pool", "paypal_promotion_proxy_pool", "paypal_provider_proxy_pool" }`; all three pools are required newline-delimited strings for US Checkout/Approve, VN Promotion Update, and TR Provider respectively. -- `GET /api/extract/{job_id}` to poll queued/running/completed status. - -The server binds to the address you pass with `--listen`. Use loopback (`IP_REDACTED` or `localhost`) for local operation; the UI does not print the access token or proxy credentials in the result view. iDEAL browser extraction uses its Checkout pool for the main route and its Promotion pool only for the ChatGPT Promotion Update call. PayPal browser extraction uses the US pool for Checkout plus approve/poll, the VN pool only for ChatGPT Promotion Update, and the TR pool for Stripe Init, tax-region updates, PaymentMethod, confirm, and external PayPal redirect resolution. The three PayPal pools rotate independently per full rebuild attempt. The web API runs extraction through a bounded FIFO queue so concurrent browser submissions do not execute all at once; excess accepted jobs show queued status, and a full queue returns HTTP `429`. - -Extraction requests without an activated CDK/session return HTTP `401`. Activated users with no remaining CDK uses receive HTTP `403`. - -LinuxDo OAuth is configured with environment variables: - -```bash -export DATABASE_URL='postgres://user:password@host:5432/ideal_link_extractor' -export LINUXDO_CLIENT_ID='your-linuxdo-client-id' -export LINUXDO_CLIENT_SECRET='your-linuxdo-client-secret' -export LINUXDO_REDIRECT_URI='http://IP_REDACTED:8793/api/oauth/linuxdo' -``` - -Optional overrides: - -```bash -export LINUXDO_MIN_TRUST_LEVEL=0 -export LINUX_DO_TOKEN_ENDPOINT='https://connect.linux.do/oauth2/token' -export LINUX_DO_USER_ENDPOINT='https://connect.linux.do/api/user' -``` - -LinuxDo application settings: - -- 应用名: `iDEAL 链接提取器` -- 应用主页: the public page URL, for example `http://IP_REDACTED:8793/` locally. -- 应用描述: `使用 LinuxDo 登录后提取 iDEAL 链接,每个账号 10 次成功提取额度。` -- 回调地址: the same value as `LINUXDO_REDIRECT_URI`, for example `http://IP_REDACTED:8793/api/oauth/linuxdo`. -- 应用图标: a public image URL you control. - -Extra CDKs are pre-provisioned in PostgreSQL. Each unbound row can be activated directly from the browser or bound after the active CDK is exhausted: - -```sql -INSERT INTO auth_cdks (cdk, kind, total_uses, remaining_uses, pending_uses, active) -VALUES ('LD-EXAMPLE-0001', 'external', 10, 10, 0, false); -``` - -Queue settings are loaded from `queue-config.json` when the server starts: - -```json -{ - "worker_count": 100, - "queue_capacity": 1000 -} -``` - -- `worker_count`: maximum extraction jobs running at the same time. -- `queue_capacity`: waiting queue size before new submissions receive HTTP `429`. - -Edit `queue-config.json` whenever you want to tune capacity, then restart `cargo run -- serve ...` for the new values to take effect. If the file is missing, startup creates it with the same `100` / `1000` defaults. - -## Scope kept - -- NL bootstrap Checkout creation for iDEAL NL/EUR, so Stripe fixes the session's payment methods with `ideal` included. -- VN `POST /backend-api/payments/checkout/update` promotion update against that same NL Checkout Session. -- NL Stripe payment page init, ChatGPT tax synchronization, and Stripe tax-region update after the VN promotion refresh. -- Stripe iDEAL payment method creation. -- Stripe confirm, ChatGPT approve retry loop, Stripe redirect polling. -- Provider redirect following. -- Simple proxy region marker rewrite for checkout/provider/approve stages. - -## Scope removed - -- Legacy FastAPI job queue and cancel endpoints; the Rust browser API uses its own bounded `/api/extract` queue and status polling endpoint. -- PayPal/GoPay/hosted flows. -- Diagnostics JSON writer. -- Proxy IP/country probes. -- DNS pre-resolve/cache. -- Browser/Playwright approval modes. -- Approved-proxy cache. +# qwen2API Enterprise Gateway + +[![License](https://img.shields.io/github/license/YuJunZhiXue/qwen2API?style=flat-square)](https://github.com/YuJunZhiXue/qwen2API/blob/main/LICENSE) +[![Stars](https://img.shields.io/github/stars/YuJunZhiXue/qwen2API?style=flat-square)](https://github.com/YuJunZhiXue/qwen2API/stargazers) +[![Forks](https://img.shields.io/github/forks/YuJunZhiXue/qwen2API?style=flat-square)](https://github.com/YuJunZhiXue/qwen2API/network/members) +[![Release](https://img.shields.io/github/v/release/YuJunZhiXue/qwen2API?style=flat-square)](https://github.com/YuJunZhiXue/qwen2API/releases) +[![Docker Pulls](https://img.shields.io/docker/pulls/yujunzhixue/qwen2api?style=flat-square)](https://hub.docker.com/r/yujunzhixue/qwen2api) + +[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/qwen2api) +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fqwen2API) + +语言 / Language: [中文](./README.md) | [English](./README.en.md) + +qwen2api 用于将通义千问(chat.qwen.ai)网页版能力转换为 OpenAI、Anthropic Claude 与 Gemini 兼容接口。项目后端基于 FastAPI,前端基于 React + Vite,内置管理台、账号池、工具调用解析、图片生成链路与多种部署方式。 + +--- + +## 目录 + +- [项目说明](#项目说明) +- [架构概览](#架构概览) +- [核心能力](#核心能力) +- [接口支持](#接口支持) +- [模型映射](#模型映射) +- [图片生成](#图片生成) +- [快速开始](#快速开始) + - [方式一:Docker 直接运行预构建镜像(推荐)](#方式一docker-直接运行预构建镜像推荐) + - [方式二:本地源码运行](#方式二本地源码运行) +- [环境变量说明(.env)](#环境变量说明env) +- [docker-compose.yml 说明](#docker-composeyml-说明) +- [端口说明](#端口说明) +- [WebUI 管理台](#webui-管理台) +- [数据持久化](#数据持久化) +- [项目目录结构](#项目目录结构) +- [高级特性与内部机制](#高级特性与内部机制) +- [性能优化与稳定性](#性能优化与稳定性) +- [客户端接入示例](#客户端接入示例) +- [常见问题](#常见问题) +- [故障排查速查表](#故障排查速查表) +- [开发指南](#开发指南) +- [变更日志与路线图](#变更日志与路线图) +- [许可证与免责声明](#许可证与免责声明) + +--- + +## 项目说明 + +本项目提供以下能力: + +1. 将千问网页对话能力转换为 OpenAI Chat Completions 接口。 +2. 将千问网页对话能力转换为 Anthropic Messages 接口。 +3. 将千问网页对话能力转换为 Gemini GenerateContent 接口。 +4. 提供独立的图片生成接口 `POST /v1/images/generations`。 +5. 支持工具调用(Tool Calling)与工具结果回传。 +6. 提供管理台,用于账号管理、API Key 管理、图片生成测试与运行状态查看。 +7. 提供多账号轮询、限流冷却、重试与浏览器 / httpx 混合引擎。 + +--- + +## 架构概览 + +```mermaid +flowchart LR + Client["🖥️ 客户端 / SDK\n(OpenAI / Claude / Gemini)"] + Upstream["☁️ chat.qwen.ai"] + + subgraph qwen2API["qwen2API(FastAPI 统一网关)"] + Router["FastAPI Router + 中间件\n(CORS / Logging / Context)"] + + subgraph Adapters["协议适配层"] + OA["OpenAI\n/v1/chat/completions"] + CA["Claude\n/anthropic/v1/messages"] + GA["Gemini\n/v1beta/models/*"] + IA["Images\n/v1/images/generations"] + FA["Files\n/v1/files"] + Admin["Admin API\n/api/admin/*"] + WebUI["WebUI\n/(静态托管)"] + end + + subgraph Runtime["运行时核心能力"] + Bridge["协议转换桥\n(多协议 <-> 统一格式)"] + Executor["Qwen Executor\n(会话管理 + 流式处理)"] + Auth["Auth Resolver\n(API key / Bearer)"] + Pool["Account Pool\n(并发控制 + 限流冷却)"] + QwenClient["Qwen Client\n(HTTP / 浏览器自动化)"] + ToolParser["Tool Parser\n(工具调用解析)"] + FileStore["File Store\n(本地文件暂存)"] + end + end + + Client --> Router + Router --> OA & CA & GA & IA & FA + Router --> Admin + Router --> WebUI + + OA & CA & GA --> Bridge + Bridge --> Executor + Executor --> Auth + Executor -.账号轮询.-> Pool + Executor -.工具调用.-> ToolParser + IA & FA --> FileStore + Auth --> QwenClient + QwenClient --> Upstream + Upstream --> QwenClient + Executor --> Bridge + Bridge --> Client +``` + +**架构说明**: + +- **后端**:Python FastAPI(`backend/`),统一处理多协议适配与上游调用 +- **前端**:React 管理台(`frontend/`),运行时托管静态构建产物 +- **部署**:Docker(推荐)、本地运行、Vercel、Zeabur + +**核心特性**: + +- **统一路由内核**:所有协议入口统一汇聚到 FastAPI Router,避免多入口行为漂移 +- **协议转换桥**:Claude / Gemini 入口先转换为统一格式,再调用上游,最后转换回原协议响应 +- **工具调用支持**:支持 OpenAI / Claude / Gemini 三种工具调用格式,自动解析与转换 +- **账号池管理**:多账号轮询、并发控制、限流冷却、自动重试 +- **文件附件**:支持文件上传、本地暂存、上下文注入 +- **图片生成**:独立图片生成接口,支持多种尺寸比例 + +--- + +## 核心能力 + +- OpenAI / Anthropic / Gemini 三套接口兼容。 +- 工具调用解析与工具结果回传。 +- Browser Engine、Httpx Engine、Hybrid Engine 三种执行模式。 +- 多账号并发池、动态冷却、故障重试。 +- 基于千问网页真实工具链路的图片生成。 +- WebUI 管理台。 +- 健康检查与就绪检查接口。 +- **Chat ID 预热池**:后台预建会话队列,单次请求节省 500ms~3s 握手耗时。 +- **Schema 压缩**:JSON Schema → TypeScript-like 签名,tool prompt 节省 ~90% 空间。 +- **工具名混淆**:客户端工具名自动加 `u_` 前缀或别名,避免 Qwen 内置函数校验拦截。 +- **工具调用幻觉防护**:auto_agent_blocked、重复调用拦截、空响应重试、毒性拒绝识别。 +- **截断自动续写**:`##TOOL_CALL##` 未闭合时自动续写并去重拼接。 +- **文件内容缓存**:代理侧缓存 Claude Code 的"Unchanged since last read"真实内容。 +- **历史拒绝清洗**:扫描历史 assistant 消息中的拒绝/自限文本,防止级联复现。 +- **增量流式 warmup**:累积 96 字符再吐出,期间过滤道歉前缀和不完整工具调用。 +- **话题隔离**:检测 user 消息的实体 Jaccard 相似度,判定新任务时自动丢弃无关历史。 +- **工具少样本注入**:按命名空间挑代表工具构造合成 few-shot,提高 MCP / Skill 类工具命中率。 +- **Edit/StrReplace 模糊匹配**:自动修复智能引号、空白、反斜杠差异导致的 exact match 失败。 +- **CLIProxy 协议转换层**:多协议入口统一落到 `StandardRequest`,避免多入口行为漂移。 + +--- + +## 接口支持 + +| 接口类型 | 路径 | 说明 | +|---|---|---| +| OpenAI Chat | `POST /v1/chat/completions` | 支持流式与非流式、工具调用、图片意图自动识别 | +| OpenAI Models | `GET /v1/models` | 返回可用模型别名 | +| OpenAI Images | `POST /v1/images/generations` | 图片生成接口 | +| Anthropic Messages | `POST /anthropic/v1/messages` | Claude / Anthropic SDK 兼容 | +| Gemini GenerateContent | `POST /v1beta/models/{model}:generateContent` | Gemini SDK 兼容 | +| Gemini Stream | `POST /v1beta/models/{model}:streamGenerateContent` | 流式输出 | +| Admin API | `/api/admin/*` | 管理接口 | +| Health | `/healthz` | 存活探针 | +| Ready | `/readyz` | 就绪探针 | + +--- + +## 模型映射 + +当前默认将主流客户端模型名称统一映射至 `qwen3.6-plus`。 + +| 传入模型名 | 实际调用 | +|---|---| +| `gpt-4o` / `gpt-4-turbo` / `gpt-4.1` / `o1` / `o3` | `qwen3.6-plus` | +| `gpt-4o-mini` / `gpt-3.5-turbo` | `qwen3.6-plus` | +| `claude-opus-4-6` / `claude-sonnet-4-6` / `claude-3-5-sonnet` | `qwen3.6-plus` | +| `claude-3-haiku` / `claude-haiku-4-5` | `qwen3.6-plus` | +| `gemini-2.5-pro` / `gemini-2.5-flash` / `gemini-1.5-pro` | `qwen3.6-plus` | +| `deepseek-chat` / `deepseek-reasoner` | `qwen3.6-plus` | + +未命中映射表时,默认回退为传入模型名本身;若管理台设置了自定义映射规则,则以配置为准。 + +--- + +## 图片生成 + +qwen2API 提供与 OpenAI Images 接口兼容的图片生成能力。 + +- 接口:`POST /v1/images/generations` +- 默认模型别名:`dall-e-3` +- 实际底层:`qwen3.6-plus` + 千问网页 `image_gen` 工具 +- 返回图片链接域名:通常为 `cdn.qwenlm.ai` + +### 请求示例 + +```bash +curl http://127.0.0.1:7860/v1/images/generations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer YOUR_API_KEY" \ + -d '{ + "model": "dall-e-3", + "prompt": "一只赛博朋克风格的猫,霓虹灯背景,超写实", + "n": 1, + "size": "1024x1024", + "response_format": "url" + }' +``` + +### 返回示例 + +```json +{ + "created": 1712345678, + "data": [ + { + "url": "https://cdn.qwenlm.ai/output/.../image.png?key=...", + "revised_prompt": "一只赛博朋克风格的猫,霓虹灯背景,超写实" + } + ] +} +``` + +### 支持的图片比例 + +前端图片生成页面内置以下比例: + +- `1:1` +- `16:9` +- `9:16` +- `4:3` +- `3:4` + +### Chat 接口图片意图识别 + +`/v1/chat/completions` 支持根据用户消息自动识别图片生成意图。例如: + +- “帮我画一张……” +- “生成一张图片……” +- “draw an image of ……” + +当识别为图片生成请求时,系统会自动切换到图片生成管道。 + +--- + +## 快速开始 + +### 方式一:Docker 直接运行预构建镜像(推荐) + +此方式适用于生产环境、测试服务器与普通部署场景。 +优点是:**不需要本地编译前端,不需要在服务器构建镜像,不需要服务器自行下载 Camoufox。** + +#### 第一步:准备目录 + +```bash +mkdir qwen2api && cd qwen2api +mkdir -p data logs +``` + +#### 第二步:创建 `docker-compose.yml` + +```yaml +services: + qwen2api: + image: yujunzhixue/qwen2api:latest + container_name: qwen2api + restart: unless-stopped + env_file: + - path: .env + required: false + ports: + - "7860:7860" + volumes: + - ./data:/workspace/data + - ./logs:/workspace/logs + shm_size: '256m' + environment: + PYTHONIOENCODING: utf-8 + PORT: "7860" + ENGINE_MODE: "hybrid" + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:7860/healthz"] + interval: 30s + timeout: 10s + start_period: 120s + retries: 3 +``` + +#### 第三步:创建 `.env`(可选但推荐) + +建议至少写入以下内容: + +```env +# ========== 必须修改 ========== +ADMIN_KEY=change-me-now # 管理台登录密钥,必须修改为强密码! + +# ========== 基础配置 ========== +PORT=7860 # 服务监听端口 +WORKERS=1 # Uvicorn worker 数量,必须保持 1(多 worker 会导致 JSON 文件冲突) +LOG_LEVEL=INFO # 日志级别:DEBUG/INFO/WARNING/ERROR + +# ========== 并发控制 ========== +MAX_INFLIGHT=1 # 每账号最大并发请求数(账号多时可改为 2) +MAX_RETRIES=3 # 请求失败最大重试次数(网络不稳定时增加到 5) + +# ========== 限流冷却 ========== +ACCOUNT_MIN_INTERVAL_MS=1200 # 同账号两次请求最小间隔(毫秒),被限流时启用 +REQUEST_JITTER_MIN_MS=120 # 请求前随机抖动最小值(毫秒) +REQUEST_JITTER_MAX_MS=360 # 请求前随机抖动最大值(毫秒) +RATE_LIMIT_BASE_COOLDOWN=600 # 限流基础冷却时间(秒),频繁限流时增加到 1200 +RATE_LIMIT_MAX_COOLDOWN=3600 # 限流最大冷却时间(秒) + +# ========== 数据文件路径(Docker 部署通常不需要改)========== +ACCOUNTS_FILE=/workspace/data/accounts.json +USERS_FILE=/workspace/data/users.json +CONTEXT_CACHE_FILE=/workspace/data/context_cache.json +UPLOADED_FILES_FILE=/workspace/data/uploaded_files.json +``` + +**环境变量详细说明**: + +| 变量 | 默认值 | 说明 | 何时修改 | +|------|--------|------|----------| +| `ADMIN_KEY` | `admin` | 管理台登录密钥 | **必须修改**为强密码 | +| `PORT` | `7860` | 服务监听端口 | 端口冲突时修改 | +| `WORKERS` | `1` | Uvicorn worker 数量 | **必须保持 1**,多 worker 会导致数据冲突 | +| `LOG_LEVEL` | `INFO` | 日志级别 | 调试时改为 `DEBUG`,生产环境改为 `WARNING` | +| `MAX_INFLIGHT` | `1` | 每账号最大并发数 | 账号多且稳定时可改为 `2` | +| `MAX_RETRIES` | `3` | 请求失败重试次数 | 网络不稳定时增加到 `5` | +| `ACCOUNT_MIN_INTERVAL_MS` | `0` | 同账号请求间隔(毫秒) | 被限流时改为 `1200` | +| `REQUEST_JITTER_MIN_MS` | `0` | 请求抖动最小值 | 模拟真实用户行为时设置 `120` | +| `REQUEST_JITTER_MAX_MS` | `0` | 请求抖动最大值 | 模拟真实用户行为时设置 `360` | +| `RATE_LIMIT_BASE_COOLDOWN` | `600` | 限流冷却时间(秒) | 频繁限流时增加到 `1200` | + +**docker-compose.yml 配置说明**: + +| 配置项 | 说明 | 建议修改 | +|--------|------|----------| +| `image` | 预构建镜像地址,支持 amd64/arm64 | 保持默认 `yujunzhixue/qwen2api:latest` | +| `ports` | 端口映射,格式:`宿主机端口:容器端口` | 如 7860 被占用,改为 `"8080:7860"` | +| `volumes` | 数据持久化挂载 | **必须保留**,否则重启后数据丢失 | +| `shm_size` | 浏览器共享内存 | 浏览器崩溃时改为 `"512m"` | +| `environment.PORT` | 容器内服务端口 | 通常不需要改 | +| `healthcheck` | 健康检查配置 | 保持默认即可 | + +#### 第四步:启动服务 + +```bash +docker compose up -d +``` + +#### 第五步:查看状态 + +```bash +docker compose ps +docker compose logs -f +curl http://127.0.0.1:7860/healthz +``` + +#### 第六步:更新服务 + +```bash +docker compose pull +docker compose up -d +``` + +--- + +## 跨平台(amd64/arm64)部署说明 + +你在 Mac(Apple Silicon, arm64)上 `docker build` 默认会产出 `linux/arm64` 镜像; +如果把这个单架构镜像推到仓库,Linux x86_64 服务器(`linux/amd64`)拉取后会报: + +`The requested image's platform (linux/arm64/v8) does not match the detected host platform (linux/amd64/...)` + +正确做法是发布 **多架构镜像(manifest list)**,同时包含 `linux/amd64` 与 `linux/arm64`。 + +### 方案 A:用 GitHub Actions 自动发布多架构镜像(推荐) + +本仓库已在 [docker-publish.yml](file:///Users/hongyan/work/workspace/todo/ai/qwen2API/.github/workflows/docker-publish.yml) 配置 `platforms: linux/amd64,linux/arm64`。 +你只需要把修复推到你自己的仓库并设置 DockerHub secrets,然后在服务器端执行: + +```bash +docker compose pull +docker compose up -d +``` + +### 方案 B:本地 buildx 推多架构镜像(适合无 CI 的场景) + +```bash +# 1) 登录镜像仓库(DockerHub/ACR/GHCR 任意) +docker login + +# 2) 构建并推送多架构镜像 +./scripts/buildx-push.sh <你的仓库名>/qwen2api: +``` + +服务器端仍然只需要 `docker compose pull && docker compose up -d`。 + +### 关于 docker-compose 文件 + +生产部署(Linux/Windows)建议使用拉镜像模式: + +- `docker-compose.yml`:默认 `image: yujunzhixue/qwen2api:latest`(或通过 `QWEN2API_IMAGE` 覆盖) +- `docker-compose.build.yml`:仅用于本地从源码构建(开发/调试) + +--- + +### 方式二:本地源码运行 + +此方式适用于本地开发与调试。 + +#### 环境要求 + +- Python 3.12+ +- Node.js 20+ +- 可访问 Camoufox 下载源 + +#### 步骤 + +```bash +git clone https://github.com/YuJunZhiXue/qwen2API.git +cd qwen2API +python start.py +``` + +`python start.py` 会自动完成以下工作: + +1. 安装后端依赖 +2. 下载 Camoufox 浏览器内核 +3. 安装前端依赖 +4. 构建前端 +5. 启动后端服务 + +--- + +## 环境变量说明(.env) + +项目提供 `.env.example` 作为模板。以下为主要参数说明。 + +### 基础参数 + +| 参数 | 默认值 | 说明 | +|---|---|---| +| `ADMIN_KEY` | `change-me-now` / `admin` | 管理台管理员密钥。建议部署后立即修改。 | +| `PORT` | `7860` | 后端服务监听端口。 | +| `WORKERS` | `1` 或 `3` | Uvicorn worker 数量。单实例环境建议 1。 | +| `REGISTER_SECRET` | 空 | 用户注册密钥。为空时表示不限制注册。 | + +### 引擎参数 + +| 参数 | 默认值 | 说明 | +|---|---|---| +| `ENGINE_MODE` | `hybrid` | 引擎模式。可选 `hybrid`、`httpx`、`browser`。 | +| `BROWSER_POOL_SIZE` | `2` | 浏览器页面池大小。值越大并发越高,但内存占用也越高。 | +| `STREAM_KEEPALIVE_INTERVAL` | `5` | 流式输出 keepalive 间隔。 | + +#### `ENGINE_MODE` 说明 + +- `hybrid`:推荐模式。聊天、建会话、删会话优先走浏览器;httpx 作为故障兜底。 +- `httpx`:全部优先走 httpx / curl_cffi。速度更快,但浏览器特征更弱,适合对速度优先的测试场景。 +- `browser`:全部走浏览器。更接近真实网页环境,但资源占用更高。 + +如果需要在 `httpx` 和 `hybrid` 之间切换,只需修改: + +```env +ENGINE_MODE=httpx +``` + +或: + +```env +ENGINE_MODE=hybrid +``` + +修改后重启服务: + +```bash +docker compose restart +``` + +### 并发与风控参数 + +| 参数 | 默认值 | 说明 | +|---|---|---| +| `MAX_INFLIGHT` | `1` | 每个账号允许的最大并发请求数。 | +| `ACCOUNT_MIN_INTERVAL_MS` | `1200` | 同一账号两次请求之间的最小间隔。 | +| `REQUEST_JITTER_MIN_MS` | `120` | 随机抖动最小值。 | +| `REQUEST_JITTER_MAX_MS` | `360` | 随机抖动最大值。 | +| `MAX_RETRIES` | `2` | 请求失败最大重试次数。 | +| `TOOL_MAX_RETRIES` | `2` | 工具调用相关最大重试次数。 | +| `EMPTY_RESPONSE_RETRIES` | `1` | 空响应最大重试次数。 | +| `RATE_LIMIT_BASE_COOLDOWN` | `600` | 账号限流基础冷却时间(秒)。 | +| `RATE_LIMIT_MAX_COOLDOWN` | `3600` | 账号限流最大冷却时间(秒)。 | + +### 数据路径参数 + +| 参数 | 默认值 | 说明 | +|---|---|---| +| `ACCOUNTS_FILE` | `/workspace/data/accounts.json` | 账号数据文件路径。 | +| `USERS_FILE` | `/workspace/data/users.json` | API Key / 用户数据文件路径。 | +| `CAPTURES_FILE` | `/workspace/data/captures.json` | 抓取结果文件路径。 | +| `CONFIG_FILE` | `/workspace/data/config.json` | 运行时配置文件路径。 | + +--- + +## docker-compose.yml 说明 + +以下是推荐的 Compose 配置: + +```yaml +services: + qwen2api: + image: yujunzhixue/qwen2api:latest + container_name: qwen2api + restart: unless-stopped + env_file: + - path: .env + required: false + ports: + - "7860:7860" + volumes: + - ./data:/workspace/data + - ./logs:/workspace/logs + shm_size: '256m' + environment: + PYTHONIOENCODING: utf-8 + PORT: "7860" + ENGINE_MODE: "hybrid" + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:7860/healthz"] + interval: 30s + timeout: 10s + start_period: 120s + retries: 3 +``` + +### 字段说明 + +| 字段 | 说明 | +|---|---| +| `image` | 预构建镜像地址。普通部署推荐使用。 | +| `container_name` | 容器名称。 | +| `restart` | 开机或故障时自动重启。 | +| `env_file` | 从 `.env` 加载环境变量。 | +| `ports` | 将宿主机端口映射到容器端口。 | +| `volumes` | 持久化数据与日志目录。 | +| `shm_size` | 浏览器共享内存。Camoufox / Firefox 运行建议至少 256m。 | +| `environment` | Compose 中直接写入的环境变量,优先级高于镜像默认值。 | +| `healthcheck` | 容器健康检查。 | + +### 用户需要修改的部分 + +通常只需要根据部署环境修改以下内容: + +1. **端口映射** + ```yaml + ports: + - "7860:7860" + ``` + 如果服务器 7860 已占用,可以改为: + ```yaml + ports: + - "8080:7860" + ``` + +2. **引擎模式** + ```yaml + environment: + ENGINE_MODE: "hybrid" + ``` + 可改为: + ```yaml + environment: + ENGINE_MODE: "httpx" + ``` + +3. **共享内存** + ```yaml + shm_size: '256m' + ``` + 如果浏览器容易崩溃,可改为: + ```yaml + shm_size: '512m' + ``` + +4. **数据挂载目录** + ```yaml + volumes: + - ./data:/workspace/data + - ./logs:/workspace/logs + ``` + 如需自定义存储路径,可替换左侧宿主机目录。 + +--- + +## 端口说明 + +### 为什么 Docker 部署前后端在同一个端口 + +Docker 镜像中已经构建好前端静态文件,并由后端统一托管: + +- 后端 API:`http://host:7860/*` +- 前端管理台:`http://host:7860/` + +因此 **Docker 部署时默认只有一个端口 7860**。 + +### 为什么本地开发时可能不是同一个端口 + +本地开发通常有两种方式: + +1. **使用 `python start.py`** + 前端会先构建为静态文件,再由后端统一托管。此时通常仍是一个端口。 + +2. **使用前端 Vite 开发服务器单独运行** + 例如: + - 前端:`http://localhost:5173` + - 后端:`http://localhost:7860` + +这种模式仅用于前端开发调试,不是生产部署模式。 + +--- + +## WebUI 管理台 + +管理台默认由后端托管,入口为: + +```text +http://127.0.0.1:7860/ +``` + +主要页面包括: + +| 页面 | 说明 | +|---|---| +| 运行状态 | 查看整体服务状态、引擎状态与统计信息 | +| 账号管理 | 添加、测试、禁用、查看上游账号状态 | +| API Key | 管理下游调用密钥 | +| 接口测试 | 直接测试 OpenAI 对话接口 | +| 图片生成 | 图形化图片生成页面 | +| 系统设置 | 查看并修改部分运行时参数 | + +--- + +## 数据持久化 + +默认数据目录: + +- `data/accounts.json`:上游账号信息 +- `data/users.json`:下游 API Key / 用户数据 +- `data/captures.json`:抓取结果 +- `data/config.json`:运行时配置 +- `logs/`:运行日志 + +生产环境请务必持久化 `data/` 与 `logs/`。 + +--- + +## 项目目录结构 + +```text +qwen2API/ +├── backend/ # Python FastAPI 后端 +│ ├── main.py # 应用入口,注册路由 / 中间件 / 生命周期 +│ ├── api/ # 协议入口层 +│ │ ├── chat.py # OpenAI Chat Completions +│ │ ├── anthropic.py # Anthropic Messages +│ │ ├── gemini.py # Gemini GenerateContent +│ │ ├── images.py # 图片生成 +│ │ ├── files.py # 文件上传 / 管理 +│ │ ├── admin.py # 管理 API +│ │ └── models.py # 模型别名 +│ ├── adapter/ +│ │ ├── cli_proxy.py # 多协议 → StandardRequest 转换代理 +│ │ └── standard_request.py # 统一请求结构 + 客户端 profile +│ ├── core/ +│ │ ├── config.py # 全局配置 / 模型映射 +│ │ ├── request_logging.py # 请求上下文 + 链路日志 +│ │ ├── auth.py # API Key / Bearer 鉴权 +│ │ └── account_pool/ # 账号池(已拆分为子模块) +│ │ ├── pool_core.py # 池状态 / 冷却 / 淘汰 +│ │ └── pool_acquire.py # 账号获取 / 并发控制 +│ ├── runtime/ +│ │ ├── execution.py # 流式执行 + 重试指令 +│ │ └── stream_metrics.py # 流式指标埋点 +│ ├── services/ # 稳定性 / 格式转换 / 兼容层 +│ │ ├── qwen_client.py # HTTP + 浏览器双引擎 +│ │ ├── prompt_builder.py # 消息 → prompt + tools 装配 +│ │ ├── tool_parser.py # ##TOOL_CALL## 文本协议解析 +│ │ ├── tool_validator.py # 工具入参校验 +│ │ ├── tool_arg_fixer.py # 智能引号 / 模糊 Edit 修复 +│ │ ├── tool_few_shot.py # 按命名空间注入少样本 +│ │ ├── tool_name_obfuscation.py# 工具名混淆避免 Qwen 函数校验 +│ │ ├── schema_compressor.py # JSON Schema → TS-like 签名 +│ │ ├── chat_id_pool.py # chat_id 预热池 +│ │ ├── file_content_cache.py # Read 结果缓存 +│ │ ├── incremental_text_streamer.py # 流式 warmup / guard +│ │ ├── refusal_cleaner.py # 历史拒绝文本清洗 +│ │ ├── topic_isolation.py # 新任务检测 / 历史切分 +│ │ ├── truncation_recovery.py # ##TOOL_CALL## 截断续写 +│ │ ├── openai_stream_translator.py # 文本协议 → OpenAI SSE +│ │ ├── context_attachment_manager.py # 长上下文 → 附件 +│ │ ├── context_offload.py # 上下文卸载策略 +│ │ ├── context_cleanup.py # TTL 清理 +│ │ ├── auth_resolver.py # API Key → 上游账号 +│ │ ├── auth_quota.py # 下游 Key 配额 +│ │ ├── completion_bridge.py # 多协议响应桥 +│ │ ├── file_store.py # 本地文件暂存 +│ │ ├── upstream_file_uploader.py # 文件上传至千问 +│ │ ├── garbage_collector.py # 会话 / 临时文件 GC +│ │ ├── response_formatters.py # 各协议响应格式化 +│ │ ├── standard_request_builder.py +│ │ ├── attachment_preprocessor.py +│ │ ├── task_session.py +│ │ └── token_calc.py +│ ├── toolcall/ +│ │ ├── normalize.py # 工具名规范化 +│ │ ├── stream_state.py # 流式工具调用状态机 +│ │ └── formats_json.py # JSON 工具格式 +│ ├── upstream/ +│ │ └── qwen_executor.py # 会话生命周期 + 流式分发 +│ └── data/ # 运行期可写目录(accounts/users/config/...) +├── frontend/ # React + Vite 管理台 +│ ├── src/ +│ │ ├── pages/ # Dashboard / Settings / Test / Images +│ │ ├── layouts/ +│ │ └── components/ +│ └── vite.config.ts +├── docker-compose.yml +├── Dockerfile +├── start.py # 一键启动(装依赖 + 下浏览器 + 构建前端) +├── requirements.txt +├── .env.example +└── README.md +``` + +--- + +## 高级特性与内部机制 + +以下是 qwen2API 为了在"千问网页对话"这条弱约束上游上跑稳定工具调用而引入的内部模块。普通使用者可以忽略;希望深度定制或贡献代码时可参考。 + +### Chat ID 预热池(`chat_id_pool.py`) + +- **动机**:`/api/v2/chats/new` 握手耗时在健康时 500ms,抖动时可达 5~6s。 +- **做法**:服务启动后为每个可用账号预建 `target_per_account` 个 `chat_id`,请求到来直接 pop;用掉一个后台立即补位。 +- **TTL**:单条 `chat_id` 默认 30 分钟过期,过期则丢弃重建。 +- **兜底**:取不到预热 chat_id 时 fallback 到同步 `create_chat`。 + +### Schema 压缩(`schema_compressor.py`) + +把 JSON Schema 压缩成 TS-like 签名: + +``` +输入:{"type":"object","properties":{ + "file_path":{"type":"string"}, + "encoding":{"type":"string","enum":["utf-8","base64"]}}, + "required":["file_path"]} + +输出:{file_path!: string, encoding?: utf-8|base64} +``` + +- 单工具定义从 ~1.5KB 降到 ~150~250 bytes。90 个工具 ~135KB → ~15KB。 +- 输入越小,上游输出预算越多,截断率越低。 + +### 工具名混淆(`tool_name_obfuscation.py`) + +Qwen 上游会把常见短名(Read/Write/Bash/Edit…)当内置函数校验并返回"Tool X does not exists."。 + +- **显式别名**:`Read→fs_open_file`、`Bash→shell_run`、`Grep→text_search` 等。 +- **通用兜底**:其余客户端工具自动加 `u_` 前缀,如 `TaskCreate→u_TaskCreate`、`mcp__playwright__click→u_mcp__playwright__click`。 +- 出站(发往 Qwen)自动转换;入站(Qwen 返回)反向还原给客户端。 + +### 工具调用少样本(`tool_few_shot.py`) + +- **问题**:有 90+ 工具(含 MCP / Skills / Plugin 多命名空间)时,Qwen 倾向于只调用几个"熟悉"的核心工具,MCP / Skill 几乎不被主动使用。 +- **做法**:按命名空间分组挑一个代表工具,构造一条合成的 `[user → assistant]` 对话,assistant 示范**多种类型工具同时被调用**(1 个核心 + 最多 4 个第三方代表)。 +- **效果**:模型看到"assistant 在第一步就用了 5 种不同类型的工具",会复现这种多样性。 + +### 工具调用截断续写(`truncation_recovery.py`) + +- 检测:`##TOOL_CALL##` 开标签数 > `##END_CALL##` 闭标签数 → 说明某个 action block 尚未闭合。 +- 续写:丢弃全部工具定义和历史(省 token),只保留末尾 2000 字节作为 anchor,在 assistant 角色塞入 anchor + user "请从中断点继续,不要重复"。 +- 去重:`deduplicateContinuation` 去掉与已有末尾的重叠;最多续写 `MAX_AUTO_CONTINUE` 次。 + +### 文件内容缓存(`file_content_cache.py`) + +Claude Code 客户端对同一文件重复 Read 时,不重发完整内容,只发一句 "File unchanged since last read" 提示语。但 qwen2API 每次请求都新建 Qwen chat,Qwen 完全没历史,提示语毫无意义。 + +- 在代理侧按 `(api_key, file_path)` 保留最近一次真实 Read 结果 +- 检测到提示语时用缓存回填 +- 内存 LRU,最多 200 条,每条 TTL 15 分钟,按 API KEY 做 session 隔离 + +### 历史拒绝清洗(`refusal_cleaner.py`) + +扫描过往 assistant 消息里的拒绝 / 自我限制文本("I'm sorry, I cannot help..."、"我只能回答编程相关问题"、"Tool X does not exist"),命中后把整条消息内容替换为占位工具调用,防止模型看到自己的拒绝模式并级联复现。 + +### 增量流式 warmup(`incremental_text_streamer.py`) + +- **warmup**:累积 96 字符再开始输出。期间可做拒绝检测 / 格式判断。 +- **guard**:任何时候输出到客户端时都保留末尾 256 字符暂不输出,给跨 chunk 检测留空间(例如识别 `##TOOL_CALL##` 开始标记)。 +- **finish()**:结束时把剩余全部补齐。 + +### 话题隔离(`topic_isolation.py`) + +- 抽取每条 user 消息的**关键实体**:文件路径、URL、专名 / 引号字符串 / 驼峰标识符。 +- 计算最新 user 消息实体集 vs 历史 first user 实体集的 **Jaccard 相似度**。 +- 当最新 user 有自己的非空实体集且 Jaccard < 0.1 → 判定为新任务 → 调用方丢弃历史。 +- 避免用户从"读文件"转到"浏览器注册"时,旧工具调用历史误导模型。 + +### 工具参数模糊修复(`tool_arg_fixer.py`) + +- **smart quote 替换**:`" " ' '` → ASCII `" '`。 +- **Edit / StrReplace 模糊匹配**:old_string 不 exact match 时,构造 fuzzy 正则(容忍引号 / 空白 / 反斜杠)在文件里搜,唯一命中则用真实文本替换 args 里的 old_string。 + +### 账号池子模块化(`core/account_pool/`) + +原先的 `account_pool.py` 已拆分: + +- `pool_core.py`:池状态 / 冷却 / 淘汰策略 +- `pool_acquire.py`:并发控制 + 账号获取(MAX_INFLIGHT + MIN_INTERVAL + jitter) + +老文件 `account_pool_old.py` 保留仅作参考,不再引用。 + +### CLIProxy 协议转换层(`adapter/cli_proxy.py`) + +多协议入口(OpenAI / Claude / Gemini)统一通过 `CLIProxy.from_openai` / `from_anthropic` / `from_gemini` 落到 `StandardRequest`,避免三个入口各自维护 prompt 组装 / tool 装配 / client_profile 判定逻辑导致行为漂移。 + +### 运行期重试指令(`runtime/execution.py`) + +集中式重试决策,支持以下触发原因: + +| 原因 | 条件 | 处理 | +|---|---|---| +| `blocked_tool_name` | 命中已知被 Qwen 校验拦截的工具名 | 注入格式提醒 | +| `invalid_textual_tool_contract` | `##TOOL_CALL##` 格式错误 | 注入格式示例 | +| `repeated_same_tool` | 相同工具 + 相同参数重复调用 | 注入反复调用禁令 | +| `unchanged_read_result` | 刚收到 "Unchanged since last read" 又要 Read 同一文件 | 强制换工具 | +| `auto_agent_blocked` | 用户未提及 agent 却自动调 Agent | 强制不调 Agent | +| `search_no_results` | 上次 WebSearch 无结果又搜同样词 | 强制换工具 | +| `empty_upstream_response` | 上游返回空 | 换账号 + 换 chat_id 重试 | +| `toxic_refusal_early` | 流式早期识别到拒绝/幻觉 | 提前拦截 + 重试 | + +--- + +## 性能优化与稳定性 + +### Hybrid 流式模式 + +工具调用采用缓冲模式(10~30s 等完整解析),纯文本采用实时流式(首 token ~5s)。既避免流式中途吐出不完整 `##TOOL_CALL##` 被客户端解析失败,又保证聊天场景的首 token 响应速度。 + +### 浏览器优先路由 + +生产部署默认 `ENGINE_MODE=hybrid`: + +- **聊天 / 建会话 / 删会话**:优先走浏览器(Camoufox),拟态更高,限流风险低。 +- **故障兜底**:浏览器失败时自动降级到 httpx / curl_cffi。 +- 避免全 httpx 方案的账号封禁风险。 + +### 预热与池化 + +| 池 | 作用 | 命中后节省 | +|---|---|---| +| 账号池 | 多账号轮询 | 一次请求 0 握手 | +| Chat ID 预热池 | 预建会话 | 500ms~6s | +| 浏览器页面池 | 预开 Camoufox 页面 | 浏览器冷启动 3~10s | + +### 限流冷却策略 + +账号命中 429 / 风控时: + +- **基础冷却**:`RATE_LIMIT_BASE_COOLDOWN`(默认 600s) +- **指数退避**:连续触发冷却时翻倍,上限 `RATE_LIMIT_MAX_COOLDOWN`(默认 3600s) +- **冷却期自动跳过**:池获取账号时自动过滤冷却中的账号 + +### 请求抖动 + +`REQUEST_JITTER_MIN_MS` / `REQUEST_JITTER_MAX_MS` 会在每次请求前引入随机延迟,避免成百上千个请求在同一时刻打到上游导致同时限流。 + +--- + +## 客户端接入示例 + +### OpenAI Python SDK + +```python +from openai import OpenAI + +client = OpenAI( + base_url="http://127.0.0.1:7860/v1", + api_key="YOUR_API_KEY", +) + +resp = client.chat.completions.create( + model="gpt-4o", + messages=[{"role": "user", "content": "你好"}], + stream=False, +) +print(resp.choices[0].message.content) +``` + +### Anthropic Python SDK(Claude Code / Anthropic SDK 通用) + +```python +from anthropic import Anthropic + +client = Anthropic( + base_url="http://127.0.0.1:7860/anthropic", + api_key="YOUR_API_KEY", +) + +resp = client.messages.create( + model="claude-sonnet-4-6", + max_tokens=1024, + messages=[{"role": "user", "content": "你好"}], +) +print(resp.content[0].text) +``` + +### Claude Code CLI + +在 `~/.claude/settings.json` 写入: + +```json +{ + "apiKey": "YOUR_API_KEY", + "apiUrl": "http://127.0.0.1:7860/anthropic" +} +``` + +或设置环境变量: + +```bash +export ANTHROPIC_BASE_URL=http://127.0.0.1:7860/anthropic +export ANTHROPIC_API_KEY=YOUR_API_KEY +claude +``` + +### Google Gen AI Python SDK(Gemini) + +```python +from google import genai + +client = genai.Client( + api_key="YOUR_API_KEY", + http_options={"base_url": "http://127.0.0.1:7860"}, +) + +resp = client.models.generate_content( + model="gemini-2.5-pro", + contents="你好", +) +print(resp.text) +``` + +### curl 直接调用 + +```bash +# OpenAI 风格 +curl http://127.0.0.1:7860/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer YOUR_API_KEY" \ + -d '{ + "model": "gpt-4o", + "messages": [{"role": "user", "content": "你好"}], + "stream": true + }' + +# Anthropic 风格 +curl http://127.0.0.1:7860/anthropic/v1/messages \ + -H "Content-Type: application/json" \ + -H "x-api-key: YOUR_API_KEY" \ + -H "anthropic-version: 2023-06-01" \ + -d '{ + "model": "claude-sonnet-4-6", + "max_tokens": 1024, + "messages": [{"role": "user", "content": "你好"}] + }' +``` + +--- + +## 常见问题 + +### 1. `.env` 不存在会怎样 + +如果 Compose 版本支持: + +```yaml +env_file: + - path: .env + required: false +``` + +则 `.env` 不存在时仍可启动,使用镜像默认配置。 +但正式部署建议始终创建 `.env`,至少设置 `ADMIN_KEY`。 + +### 2. 服务器无法下载 Camoufox + +请使用“Docker 直接运行预构建镜像”方式。 +该方式不依赖服务器下载浏览器内核,也不需要服务器本地构建镜像。 + +### 3. 图片生成返回 500 或 no URL found + +排查步骤: + +1. 确认上游账号在网页中可正常使用图片生成。 +2. 查看日志中的 `[T2I]` 与 `[T2I-SSE]` 输出。 +3. 确认部署的是最新镜像版本。 +4. 确认前端页面未缓存旧资源。 + +### 4. `ENGINE_MODE` 选哪个 + +- 优先稳定性:`hybrid` +- 优先速度:`httpx` +- 优先网页拟态:`browser` + +生产场景默认建议使用 `hybrid`。 + +### 5. 为什么工具调用偶尔被拦截成 "Tool X does not exists." + +Qwen 上游会把常见短名(Read/Write/Bash...)当内置函数校验。qwen2API 已通过 `tool_name_obfuscation.py` 对全量工具名做别名 / `u_` 前缀处理。如果仍出现: + +- 确认没有把旧版自定义 prompt 覆盖掉默认 prompt。 +- 提 issue 并附上 `prompt 前 500 字预览` 日志。 + +### 6. 大文件 Edit / Write 报 JSON 解析失败 + +通常是上游输出被 `max_output_tokens` 截断。`truncation_recovery.py` 已经内置"检测 + 续写 + 去重"链路,偶发失败可增加 `MAX_AUTO_CONTINUE` 或缩短一次要改的范围。 + +### 7. Claude Code 调子 agent 报 "Agent type 'xxx' not found" + +Qwen 偶尔会对 `Agent` 工具的 `subagent_type` 生成客户端不认识的值(如 `"browser"`)。检查: + +- 客户端 Claude Code 实际支持的 agent 列表(`/help` 或 Claude Code 设置里)。 +- 服务端日志是否出现 `auto_agent_blocked` 重试记录;若已流出再重试只能影响下一轮。 +- 必要时在 `prompt_builder.py` 里**移除**对 Agent 工具的暴露,或在 `openai_stream_translator.py` 做 enum 合法化。 + +### 8. 账号被限流 / 冷却太频繁 + +- 增加 `ACCOUNT_MIN_INTERVAL_MS`(例如 `1500~2000`)降低单账号频率。 +- 提高 `RATE_LIMIT_BASE_COOLDOWN`(例如 `1200`)让冷却期更长,避免立刻再被限。 +- 增加账号池大小(管理台 → 账号管理 → 添加账号)。 + +### 9. WebUI 登录后立刻被登出 + +- 确认 `ADMIN_KEY` 未在运行期被修改。 +- 清理浏览器 cookie / localStorage 后重试。 +- 确认不是多 worker 跑起来(`WORKERS=1`),多 worker 会导致 session 文件写冲突。 + +### 10. 前端页面白屏 / 静态资源 404 + +- 确认使用的是预构建镜像(`yujunzhixue/qwen2api:latest`),不是空壳镜像。 +- 本地源码运行时确保 `python start.py` 已完成前端构建。 +- 检查浏览器是否缓存了旧版本 HTML,强刷(Ctrl+Shift+R)。 + +--- + +## 故障排查速查表 + +| 现象 | 可能原因 | 排查步骤 | +|------|----------|----------| +| 启动即 OOM | 浏览器页面池过大或 `shm_size` 太小 | 降低 `BROWSER_POOL_SIZE`;`shm_size: '512m'` | +| 首 token 超过 30s | 上游抖动 / 账号冷启动 | 看日志 `首个事件耗时`;开启 chat_id 预热池 | +| 响应总是空字符串 | 上游返回空(`empty_upstream_response`) | 检查账号是否被限流;换账号重试 | +| 工具调用被截成纯文本流给客户端 | 流出过早,未等 `##END_CALL##` | 检查是否错误开启了非 hybrid 模式;查看 `incremental_text_streamer` 日志 | +| 连续 Read 同一文件 | 客户端发 "Unchanged since last read";服务端未回填缓存 | 看 `file_content_cache` 是否命中;确认 api_key 一致 | +| 模型只会 Read/Write,MCP 工具不被调 | few-shot 未注入 | 确认 `[少样本] 注入 5 个代表` 日志出现 | +| `Tool X does not exists.` | 工具名未被混淆 | 确认 `tool_name_obfuscation.to_qwen_name` 被调用 | +| Agent subagent_type 报错 | Qwen 幻觉生成不存在的 agent | 参考常见问题 #7 | +| `/healthz` 返回 200,但 `/readyz` 500 | 账号池未加载或浏览器未就绪 | 看管理台账号列表;延长 `start_period` | +| 日志只有 prewarmed 没有新请求 | 客户端未打到 7860,或鉴权失败 | `curl -v http://127.0.0.1:7860/v1/models -H "Authorization: Bearer XXX"` | + +### 日志关键字速查 + +| 关键字 | 含义 | +|--------|------| +| `[CLIProxy]` | 协议转换入口,含 `prompt_len` / `tools` 数 | +| `[上游]` | 与 chat.qwen.ai 的交互,含账号 / chat_id / 耗时 | +| `[ChatIdPool]` | chat_id 预热池状态 | +| `[SessionPlan]` | 会话复用决策 | +| `[少样本]` | few-shot 注入情况 | +| `[Collect]` | 流式收集器检测到工具调用 | +| `[收集完成]` | 本次响应的最终状态(字数 / 工具调用 / finish_reason) | +| `[ToolDirective]` | 工具调用块 / stop_reason 决策 | +| `[重试]` | 运行期重试原因 | +| `[ContextCleanup]` | TTL 清理 | + +--- + +## 开发指南 + +### 本地开发环境 + +```bash +# 后端 +python -m venv .venv +source .venv/bin/activate # Windows: .venv\Scripts\activate +pip install -r backend/requirements.txt +uvicorn backend.main:app --reload --port 7860 + +# 前端(另开终端) +cd frontend +npm install +npm run dev # http://localhost:5173 +``` + +前端开发模式下 API 默认代理到 `http://localhost:7860`,见 `frontend/vite.config.ts`。 + +### 代码结构约定 + +- **协议入口**:只做协议解析,调 `CLIProxy` 转 `StandardRequest` 后交给 `qwen_executor`。 +- **业务逻辑**:放 `services/` 下的独立模块,不要写进 API 层。 +- **运行期决策**:重试 / 拦截 / 续写等集中在 `runtime/execution.py`。 +- **工具调用**:文本协议解析在 `services/tool_parser.py`,状态机在 `toolcall/stream_state.py`。 + +### 调试建议 + +| 场景 | 打开方式 | +|------|----------| +| 看 prompt 全貌 | `LOG_LEVEL=DEBUG`,grep `prompt 前 500 字预览` | +| 看流式每个 chunk | `LOG_LEVEL=DEBUG`,grep `[Collect]` | +| 看账号选择 | grep `[上游] 账号已获取` | +| 看重试 | grep `[重试]` 或 `auto_agent_blocked` | +| 看 chat_id 池 | grep `[ChatIdPool]` | +| 看 few-shot | grep `[少样本]` | + +### 增加新的上游模型别名 + +在 `backend/core/config.py` 的 `MODEL_ALIAS_MAP` 里加一行: + +```python +MODEL_ALIAS_MAP = { + ... + "my-custom-model": "qwen3.6-plus", +} +``` + +或通过管理台 → 系统设置 → 模型映射 动态配置(热生效,不需重启)。 + +### 增加客户端 profile + +不同客户端(Claude Code / Cursor / Codex / Cline ...)对 tool 协议略有差异。新客户端需要: + +1. 在 `backend/adapter/standard_request.py` 定义 profile 常量。 +2. 在 `backend/services/prompt_builder.py` 的 profile 分支里加入对应 prompt 模板。 +3. 在 `backend/services/openai_stream_translator.py` 处理该 profile 的输出 quirks。 + +### 运行单元测试 + +```bash +pytest backend/tests -v +``` + +(项目后续会补齐 services 层单测;当前以真实 API 冒烟为主。) + +### 贡献流程 + +1. Fork 仓库并拉取 feature 分支。 +2. 保持单个 PR 聚焦一件事。 +3. 如果改动涉及上游协议或 prompt 模板,**附 2~3 条真实上游日志**作为佐证。 +4. 不建议在 PR 里混 lint 整理(diff 噪声大)。 +5. 欢迎提 issue 描述场景 + 日志片段,维护者会评估后分流。 + +--- + +## 变更日志与路线图 + +### 已完成 + +- [x] OpenAI / Anthropic / Gemini 三协议统一适配 +- [x] Browser / Httpx / Hybrid 三引擎 + 故障兜底 +- [x] 账号池 + 限流冷却 + 抖动 +- [x] Chat ID 预热池 +- [x] 浏览器页面池 +- [x] 文件上传 + 附件注入 +- [x] 图片生成(`/v1/images/generations`) +- [x] 工具名混淆避免 Qwen 内置函数拦截 +- [x] Schema 压缩 + 少样本注入 +- [x] 截断自动续写 + 去重 +- [x] 文件内容缓存 + 话题隔离 +- [x] 历史拒绝清洗 +- [x] 增量流式 warmup / guard +- [x] 运行期重试指令集中决策 +- [x] WebUI:账号管理 / API Key / 接口测试 / 图片生成 / 系统设置 + +### 计划中 + +- [ ] Agent 工具 `subagent_type` 的 enum 合法化兜底 +- [ ] 工具调用缓冲下发(避免早期幻觉参数流给客户端) +- [ ] services 层单元测试覆盖 +- [ ] Prometheus 指标导出 +- [ ] 多后端模型(豆包 / 智谱等)并行接入作为故障兜底 +- [ ] WebUI 日志查看 / 账号健康监控看板 + +> 若你有强需求,欢迎在 issue 里 +1 推高优先级。 + +--- + +## 许可证与免责声明 + +### 开源许可证 + +本项目采用 **MIT License** 发布。你可以根据 MIT License 的条款使用、复制、修改、分发本项目源代码,但必须保留原始版权声明与许可证文本。 + +### 使用范围说明 + +本项目用于协议兼容、接口转换、自动化测试与个人技术研究。项目本身不提供任何官方授权的通义千问商业接口服务。 + +### 免责声明 + +1. 本项目与阿里云、通义千问及相关官方服务无任何从属、代理或商业合作关系。 +2. 本项目不是官方产品,也不构成任何官方服务承诺。 +3. 使用者应自行评估所在地区的法律法规、上游服务条款、账号合规性与数据安全要求。 +4. 因使用本项目导致的账号封禁、请求受限、数据丢失、服务中断、法律纠纷或其他风险,由使用者自行承担责任。 +5. 项目维护者不对任何直接或间接损失承担责任。 +6. 不建议将本项目用于违反上游服务条款、违反法律法规或存在明显合规风险的场景。 + +如果权利人认为本项目内容侵犯其合法权益,请通过仓库 Issue 或其他公开联系方式提出,维护者将在核实后处理。 diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c50b236a0a0030ac68f131da12d4aa06ab3785d1 --- /dev/null +++ b/backend/__init__.py @@ -0,0 +1 @@ +# Backend package diff --git a/backend/accounts.json b/backend/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..7d440307b9b68837edaaf214a4545e977f758e2a --- /dev/null +++ b/backend/accounts.json @@ -0,0 +1,13 @@ +[ + { + "email": "test@test.com", + "token": "fake_token", + "password": "test", + "is_valid": true, + "last_used": 0, + "inflight": 0, + "activation_pending": false, + "created_at": 1712534400, + "rate_limited_until": 0 + } +] diff --git a/backend/adapter/__init__.py b/backend/adapter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5610ff8d3729e43956fcfcbbb3902592a570b4f5 --- /dev/null +++ b/backend/adapter/__init__.py @@ -0,0 +1 @@ +from .standard_request import StandardRequest diff --git a/backend/adapter/cli_proxy.py b/backend/adapter/cli_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..7168ec1d41f1042ce64c28e35ad6c6305cf722a2 --- /dev/null +++ b/backend/adapter/cli_proxy.py @@ -0,0 +1,258 @@ +""" +CLIProxy - 协议转换代理层 +统一处理 OpenAI/Claude/Gemini 协议到 StandardRequest 的转换 +""" +import logging +from typing import Any + +from backend.adapter.standard_request import StandardRequest, CLAUDE_CODE_OPENAI_PROFILE +from backend.core.config import resolve_model +from backend.services.prompt_builder import messages_to_prompt +from backend.toolcall.normalize import build_tool_name_registry + +log = logging.getLogger("qwen2api.cli_proxy") + + +class CLIProxy: + """ + 协议转换代理 - 类似 ds2api 的 CLIProxy + 负责将不同协议(OpenAI/Claude/Gemini)转换为统一的 StandardRequest + """ + + @staticmethod + def from_openai(req_data: dict, *, client_profile: str = CLAUDE_CODE_OPENAI_PROFILE) -> StandardRequest: + """ + OpenAI 协议 -> StandardRequest + + Args: + req_data: OpenAI 格式的请求体 + client_profile: 客户端配置文件 + + Returns: + StandardRequest: 统一的标准请求对象 + """ + model_name = req_data.get("model", "gpt-4o") + prompt_result = messages_to_prompt(req_data, client_profile=client_profile) + + tools = prompt_result.tools + tool_names = [ + tool_name + for tool_name in (tool.get("name") for tool in tools) + if isinstance(tool_name, str) and tool_name + ] + + return StandardRequest( + prompt=prompt_result.prompt, + response_model=model_name, + resolved_model=resolve_model(model_name), + surface="openai", + client_profile=client_profile, + requested_model=model_name, + stream=req_data.get("stream", False), + tools=tools, + tool_names=tool_names, + tool_name_registry=build_tool_name_registry(tool_names), + tool_enabled=prompt_result.tool_enabled, + ) + + @staticmethod + def from_anthropic(req_data: dict, *, client_profile: str = CLAUDE_CODE_OPENAI_PROFILE) -> StandardRequest: + """ + Anthropic Claude 协议 -> StandardRequest + + Args: + req_data: Claude 格式的请求体 + client_profile: 客户端配置文件 + + Returns: + StandardRequest: 统一的标准请求对象 + """ + model_name = req_data.get("model", "claude-3-5-sonnet") + prompt_result = messages_to_prompt(req_data, client_profile=client_profile) + + tools = prompt_result.tools + tool_names = [ + tool_name + for tool_name in (tool.get("name") for tool in tools) + if isinstance(tool_name, str) and tool_name + ] + + return StandardRequest( + prompt=prompt_result.prompt, + response_model=model_name, + resolved_model=resolve_model(model_name), + surface="anthropic", + client_profile=client_profile, + requested_model=model_name, + stream=req_data.get("stream", False), + tools=tools, + tool_names=tool_names, + tool_name_registry=build_tool_name_registry(tool_names), + tool_enabled=prompt_result.tool_enabled, + ) + + @staticmethod + def from_gemini(model: str, req_data: dict, *, stream: bool | None = None) -> StandardRequest: + """ + Google Gemini 协议 -> StandardRequest + + Args: + model: Gemini 模型名称 + req_data: Gemini 格式的请求体 + stream: 是否流式输出(None 则从请求体推断) + + Returns: + StandardRequest: 统一的标准请求对象 + """ + prompt = CLIProxy._extract_gemini_prompt(req_data) + stream_requested = CLIProxy._is_gemini_stream_request(req_data) if stream is None else stream + + # Gemini 暂不支持工具调用,后续可扩展 + tools = [] + tool_names = [] + + return StandardRequest( + prompt=prompt, + response_model=model, + resolved_model=resolve_model(model), + surface="gemini", + requested_model=model, + content=prompt, + stream=stream_requested, + tools=tools, + tool_names=tool_names, + tool_name_registry={}, + tool_enabled=False, + ) + + @staticmethod + def _extract_gemini_prompt(body: dict) -> str: + """从 Gemini 请求体中提取 prompt""" + lines: list[str] = [] + for message in body.get("contents", []) or []: + if message.get("role") != "user": + continue + for part in message.get("parts", []) or []: + text = part.get("text") + if text: + lines.append(text) + return "\n".join(lines) + + @staticmethod + def _is_gemini_stream_request(body: dict[str, Any]) -> bool: + """判断 Gemini 请求是否为流式""" + if body.get("stream") is True: + return True + generation_config = body.get("generationConfig") + if isinstance(generation_config, dict) and generation_config.get("stream") is True: + return True + return False + + @staticmethod + def to_openai_response(execution, standard_request: StandardRequest) -> dict: + """ + StandardRequest 执行结果 -> OpenAI 响应格式 + + Args: + execution: 执行结果对象 + standard_request: 原始标准请求 + + Returns: + dict: OpenAI 格式的响应 + """ + return { + "id": f"chatcmpl-{execution.chat_id[:12]}", + "object": "chat.completion", + "created": int(execution.state.created_at or 0), + "model": standard_request.response_model, + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": execution.state.answer_text, + }, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": len(standard_request.prompt), + "completion_tokens": len(execution.state.answer_text), + "total_tokens": len(standard_request.prompt) + len(execution.state.answer_text), + }, + } + + @staticmethod + def to_anthropic_response(execution, standard_request: StandardRequest, msg_id: str, directive) -> dict: + """ + StandardRequest 执行结果 -> Anthropic Claude 响应格式 + + Args: + execution: 执行结果对象 + standard_request: 原始标准请求 + msg_id: 消息 ID + directive: 工具调用指令 + + Returns: + dict: Claude 格式的响应 + """ + content_blocks: list[dict] = [] + + # 添加思考内容 + if execution.state.reasoning_text: + content_blocks.append({"type": "thinking", "thinking": execution.state.reasoning_text}) + + # 添加工具调用块 + content_blocks.extend(directive.tool_blocks) + + return { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": standard_request.response_model, + "content": content_blocks, + "stop_reason": directive.stop_reason, + "stop_sequence": None, + "usage": { + "input_tokens": len(standard_request.prompt), + "output_tokens": len(execution.state.answer_text), + }, + } + + @staticmethod + def to_gemini_response(execution, standard_request: StandardRequest) -> dict: + """ + StandardRequest 执行结果 -> Google Gemini 响应格式 + + Args: + execution: 执行结果对象 + standard_request: 原始标准请求 + + Returns: + dict: Gemini 格式的响应 + """ + return { + "candidates": [ + { + "content": { + "parts": [{"text": execution.state.answer_text}], + "role": "model", + }, + "finishReason": "STOP", + "index": 0, + } + ], + "usageMetadata": { + "promptTokenCount": len(standard_request.prompt), + "candidatesTokenCount": len(execution.state.answer_text), + "totalTokenCount": len(standard_request.prompt) + len(execution.state.answer_text), + }, + } + + @staticmethod + def log_conversion(surface: str, model: str, prompt_len: int, tool_count: int): + """记录协议转换日志""" + log.info( + f"[CLIProxy] {surface.upper()} -> StandardRequest: " + f"model={model}, prompt_len={prompt_len}, tools={tool_count}" + ) diff --git a/backend/adapter/standard_request.py b/backend/adapter/standard_request.py new file mode 100644 index 0000000000000000000000000000000000000000..85648b01cab30f63e58d4dae039f1dcdbf6e4c0f --- /dev/null +++ b/backend/adapter/standard_request.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from backend.runtime.attachment_types import NormalizedAttachment + +CLAUDE_CODE_OPENAI_PROFILE = "claude_code_openai" +OPENCLAW_OPENAI_PROFILE = "openclaw_openai" + + +@dataclass(slots=True) +class StandardRequest: + prompt: str + response_model: str + resolved_model: str + surface: str + client_profile: str = OPENCLAW_OPENAI_PROFILE + requested_model: str | None = None + content: str | None = None + stream: bool = False + tools: list[dict[str, Any]] = field(default_factory=list) + tool_names: list[str] = field(default_factory=list) + tool_name_registry: dict[str, str] = field(default_factory=dict) + tool_enabled: bool = False + attachments: list[NormalizedAttachment] = field(default_factory=list) + uploaded_file_ids: list[str] = field(default_factory=list) + upstream_files: list[dict[str, Any]] = field(default_factory=list) + session_key: str | None = None + context_mode: str = "inline" + bound_account_email: str | None = None + bound_account: Any | None = None + stage_labels: dict[str, str] = field(default_factory=dict) + full_prompt: str | None = None + upstream_chat_id: str | None = None + persistent_session: bool = False + session_message_hashes: list[str] = field(default_factory=list) + session_chat_invalidated: bool = False diff --git a/backend/api/__init__.py b/backend/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/api/admin.py b/backend/api/admin.py new file mode 100644 index 0000000000000000000000000000000000000000..c731547987d5e9485616e1ac6ce66d45eefe74f9 --- /dev/null +++ b/backend/api/admin.py @@ -0,0 +1,342 @@ +from fastapi import APIRouter, Depends, HTTPException, Header, Request +from pydantic import BaseModel +from backend.core.config import settings +from backend.core.database import AsyncJsonDB +from backend.core.account_pool import AccountPool, Account +import secrets + +router = APIRouter() + +def verify_admin(authorization: str = Header(None)): + if not authorization or not authorization.startswith("Bearer "): + raise HTTPException(status_code=401, detail="Unauthorized") + token = authorization.split("Bearer ")[1] + + from backend.core.config import API_KEYS, settings as backend_settings + + # 允许使用默认管理员 Key (ADMIN_KEY) 或者任何已生成的 API_KEYS 作为管理凭证 + if token != backend_settings.ADMIN_KEY and token not in API_KEYS: + raise HTTPException(status_code=403, detail="Forbidden: Admin Key Mismatch") + return token + +class UserCreate(BaseModel): + name: str + quota: int = 1000000 + +class User(BaseModel): + id: str + name: str + quota: int + used_tokens: int + +@router.get("/status", dependencies=[Depends(verify_admin)]) +async def get_system_status(request: Request): + pool = request.app.state.account_pool + + # 账号层细粒度 inflight / 状态 + per_account = [] + for acc in getattr(pool, "accounts", []): + per_account.append({ + "email": acc.email, + "status": acc.get_status_code(), + "inflight": getattr(acc, "inflight", 0), + "max_inflight": getattr(pool, "max_inflight_per_account", 0), + "consecutive_failures": getattr(acc, "consecutive_failures", 0), + "rate_limit_strikes": getattr(acc, "rate_limit_strikes", 0), + "last_request_finished": getattr(acc, "last_request_finished", 0), + }) + + # chat_id 预热池指标(若已启用) + chat_id_pool_stats = None + cp = getattr(request.app.state, "chat_id_pool", None) + if cp is not None: + try: + per_account_pool: dict[str, int] = {} + for acc in getattr(pool, "accounts", []): + per_account_pool[acc.email] = await cp.size(acc.email) + chat_id_pool_stats = { + "total_cached": await cp.total_size(), + "target_per_account": cp._target, + "ttl_seconds": cp._ttl, + "per_account": per_account_pool, + } + except Exception: + chat_id_pool_stats = {"error": "snapshot failed"} + + # 向运行时拿全局任务计数 / asyncio 状态 + import asyncio + try: + tasks = asyncio.all_tasks() + running_tasks = sum(1 for t in tasks if not t.done()) + except Exception: + running_tasks = -1 + + return { + "accounts": pool.status(), + "per_account": per_account, + "chat_id_pool": chat_id_pool_stats, + "runtime": { + "asyncio_running_tasks": running_tasks, + }, + "request_runtime": { + "mode": "direct_http", + "browser_required_for_requests": False, + "description": "普通请求直连 HTTP,不经过浏览器", + }, + "browser_automation": { + "mode": "on_demand_registration_only", + "description": "仅注册/激活/刷新 Token 时按需启动真实浏览器", + } + } + +@router.get("/users", dependencies=[Depends(verify_admin)]) +async def list_users(request: Request): + db: AsyncJsonDB = request.app.state.users_db + data = await db.get() + return {"users": data} + +@router.post("/users", dependencies=[Depends(verify_admin)]) +async def create_user(user: UserCreate, request: Request): + import uuid + db: AsyncJsonDB = request.app.state.users_db + data = await db.get() + new_user = { + "id": f"sk-{uuid.uuid4().hex}", + "name": user.name, + "quota": user.quota, + "used_tokens": 0 + } + data.append(new_user) + await db.save(data) + return new_user + +@router.post("/accounts", dependencies=[Depends(verify_admin)]) +async def add_account(request: Request): + import time + from backend.core.account_pool import Account, AccountPool + from backend.services.qwen_client import QwenClient + + pool: AccountPool = request.app.state.account_pool + client: QwenClient = request.app.state.qwen_client + + try: + data = await request.json() + except Exception: + raise HTTPException(400, detail="Invalid JSON body") + + token = data.get("token", "") + if not token: + raise HTTPException(400, detail="token is required") + + acc = Account( + email=data.get("email", f"manual_{int(time.time())}@qwen"), + password=data.get("password", ""), + token=token, + cookies=data.get("cookies", ""), + username=data.get("username", "") + ) + + is_valid = await client.verify_token(token) + if not is_valid: + return {"ok": False, "error": "Invalid token (验证失败,请确认Token有效)"} + + await pool.add(acc) + return {"ok": True, "email": acc.email} + + +@router.get("/accounts", dependencies=[Depends(verify_admin)]) +async def list_accounts(request: Request): + pool: AccountPool = request.app.state.account_pool + # 模拟原始 FastAPI 序列化,包含运行时状态 + accs = [] + for a in pool.accounts: + d = a.to_dict() + d["valid"] = a.valid + d["inflight"] = a.inflight + d["rate_limited_until"] = a.rate_limited_until + accs.append(d) + return {"accounts": accs} + +@router.post("/accounts/register", dependencies=[Depends(verify_admin)]) +async def register_new_account(request: Request): + """一键调用浏览器无头注册新千问账号""" + import logging + from backend.services.auth_resolver import register_qwen_account + from backend.core.account_pool import AccountPool + pool: AccountPool = request.app.state.account_pool + + log = logging.getLogger("backend.api.admin") + + client_ip = request.client.host if request.client else "127.0.0.1" + log.info(f"[注册] 管理员触发注册,来源IP: {client_ip}") + + # 简单的频率限制保护 + current = len(pool.accounts) + if current >= 100: + return {"ok": False, "error": "账号池已满,请先清理死号"} + + try: + acc = await register_qwen_account() + if acc: + await pool.add(acc) + log.info(f"[注册] 注册成功: {acc.email}(当前账号数: {len(pool.accounts)}/100)") + return {"ok": True, "email": acc.email, "message": "新账号注册成功并已入池"} + return {"ok": False, "error": "自动化注册失败,可能遇到风控或页面元素改变"} + except Exception as e: + return {"ok": False, "error": f"注册发生异常: {str(e)}"} + +@router.post("/verify", dependencies=[Depends(verify_admin)]) +async def verify_all_accounts(request: Request): + """验证所有账号的有效性 (完全复原单文件逻辑)""" + from backend.core.account_pool import AccountPool + from backend.services.qwen_client import QwenClient + import logging + + log = logging.getLogger("qwen2api.admin") + pool: AccountPool = request.app.state.account_pool + client: QwenClient = request.app.state.qwen_client + + results = [] + for acc in pool.accounts: + is_valid = await client.verify_token(acc.token) + if not is_valid and acc.password: + log.info(f"[校验] {acc.email} token失效,尝试自动刷新...") + is_valid = await client.auth_resolver.refresh_token(acc) + + acc.valid = is_valid + results.append({"email": acc.email, "valid": is_valid, "refreshed": not is_valid}) + + await pool.save() # 直接保存全部状态,不调用 mark_invalid 以免熔断影响测试 + return {"ok": True, "results": results} + +@router.post("/accounts/{email}/activate", dependencies=[Depends(verify_admin)]) +async def activate_account(email: str, request: Request): + """单独激活某个账号""" + from backend.services.auth_resolver import activate_account as activate_logic + from backend.core.account_pool import AccountPool + + pool: AccountPool = request.app.state.account_pool + acc = next((a for a in pool.accounts if a.email == email), None) + if not acc: + raise HTTPException(status_code=404, detail="Account not found") + + # 防止并发点击:检查一个运行时标志 + if getattr(acc, "_is_activating", False): + return {"ok": False, "error": "该账号正在激活中,请勿重复点击"} + + try: + setattr(acc, "_is_activating", True) + success = await activate_logic(acc) + if success: + acc.valid = True + acc.activation_pending = False + await pool.add(acc) # 这会触发覆盖保存 + return {"ok": True, "message": "账号激活成功"} + return {"ok": False, "error": "未能找到激活链接或获取Token"} + finally: + setattr(acc, "_is_activating", False) + +@router.post("/accounts/{email}/verify", dependencies=[Depends(verify_admin)]) +async def verify_account(email: str, request: Request): + """单独验证某个账号的有效性 (完全复原单文件逻辑)""" + from backend.services.qwen_client import QwenClient + from backend.core.account_pool import AccountPool + import logging + + log = logging.getLogger("qwen2api.admin") + pool: AccountPool = request.app.state.account_pool + client: QwenClient = request.app.state.qwen_client + + acc = next((a for a in pool.accounts if a.email == email), None) + if not acc: + raise HTTPException(status_code=404, detail="Account not found") + + is_valid = await client.verify_token(acc.token) + if not is_valid and acc.password: + log.info(f"[校验] {acc.email} token失效,尝试自动刷新...") + is_valid = await client.auth_resolver.refresh_token(acc) + + acc.valid = is_valid + await pool.save() # 直接保存,不调用 mark_invalid 以免熔断影响正常测试 + + return {"email": acc.email, "valid": is_valid} + +@router.delete("/accounts/{email}", dependencies=[Depends(verify_admin)]) +async def delete_account(email: str, request: Request): + from backend.core.account_pool import AccountPool + pool: AccountPool = request.app.state.account_pool + await pool.remove(email) + return {"ok": True} + +@router.get("/settings", dependencies=[Depends(verify_admin)]) +async def get_settings(request: Request): + from backend.core.config import MODEL_MAP + from backend.core.config import settings as backend_settings + + safe_map = {k: v for k, v in MODEL_MAP.items()} + pool = getattr(request.app.state, "chat_id_pool", None) + acc_pool = getattr(request.app.state, "account_pool", None) + return { + "version": "2.0.0", + "max_inflight_per_account": backend_settings.MAX_INFLIGHT_PER_ACCOUNT, + "global_max_inflight": getattr(acc_pool, "global_max_inflight", 0), + "max_queue_size": getattr(acc_pool, "max_queue_size", 0), + "chat_id_pool_target": pool.target if pool else 0, + "chat_id_pool_ttl_seconds": pool.ttl if pool else 0, + "model_aliases": safe_map, + } + +@router.put("/settings", dependencies=[Depends(verify_admin)]) +async def update_settings(data: dict, request: Request): + from backend.core.config import MODEL_MAP + if "max_inflight_per_account" in data: + try: + val = int(data["max_inflight_per_account"]) + settings.MAX_INFLIGHT_PER_ACCOUNT = val + pool = getattr(request.app.state, "account_pool", None) + if pool is not None and hasattr(pool, "set_max_inflight"): + pool.set_max_inflight(val) + except (TypeError, ValueError): + pass + if "global_max_inflight" in data: + try: + val = int(data["global_max_inflight"]) + pool = getattr(request.app.state, "account_pool", None) + if pool is not None and val > 0: + pool.global_max_inflight = val + except (TypeError, ValueError): + pass + if "chat_id_pool_target" in data or "chat_id_pool_ttl_seconds" in data: + cp = getattr(request.app.state, "chat_id_pool", None) + if cp is not None: + cp.update_config( + target=data.get("chat_id_pool_target"), + ttl_seconds=data.get("chat_id_pool_ttl_seconds"), + ) + if "model_aliases" in data: + MODEL_MAP.clear() + MODEL_MAP.update(data["model_aliases"]) + return {"ok": True} + +@router.get("/keys", dependencies=[Depends(verify_admin)]) +async def get_keys(): + from backend.core.config import API_KEYS + return {"keys": list(API_KEYS)} + +@router.post("/keys", dependencies=[Depends(verify_admin)]) +async def create_key(): + from backend.core.config import API_KEYS, save_api_keys + + new_key = f"sk-{secrets.token_hex(24)}" + API_KEYS.add(new_key) + save_api_keys(API_KEYS) + return {"ok": True, "key": new_key} + +@router.delete("/keys/{key}", dependencies=[Depends(verify_admin)]) +async def delete_key(key: str): + from backend.core.config import API_KEYS, save_api_keys + + if key in API_KEYS: + API_KEYS.remove(key) + save_api_keys(API_KEYS) + return {"ok": True} diff --git a/backend/api/anthropic.py b/backend/api/anthropic.py new file mode 100644 index 0000000000000000000000000000000000000000..29fc2da7360adfada9191a80c9dff672d14493b7 --- /dev/null +++ b/backend/api/anthropic.py @@ -0,0 +1,513 @@ +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse, StreamingResponse +import asyncio +import json +import logging +import uuid + +from backend.adapter.standard_request import StandardRequest +from backend.adapter.cli_proxy import CLIProxy +from backend.core.config import resolve_model, settings +from backend.core.request_logging import new_request_id, request_context, update_request_context +from backend.runtime import stream_presenter +from backend.runtime.execution import ( + build_tool_directive, + cleanup_runtime_resources, + collect_completion_run, + collect_completion_run_with_recovery, + evaluate_retry_directive, + request_max_attempts, +) +from backend.services.auth_quota import resolve_auth_context +from backend.services.context_attachment_manager import prepare_context_attachments, derive_session_key +from backend.services.attachment_preprocessor import preprocess_attachments +from backend.services.prompt_builder import CLAUDE_CODE_OPENAI_PROFILE, messages_to_prompt +from backend.services.qwen_client import QwenClient +from backend.services.task_session import ( + build_anthropic_assistant_history_message, + build_retry_rebase_prompt, + clear_invalidated_session_chat, + log_session_plan_reuse_cancelled, + persist_session_turn, + plan_persistent_session_turn, +) +from backend.services.token_calc import count_tokens +from backend.toolcall.normalize import build_tool_name_registry + +log = logging.getLogger("qwen2api.anthropic") +router = APIRouter() + + +class _AnthropicStreamState: + def __init__(self, *, msg_id: str, model_name: str, prompt: str): + self.msg_id = msg_id + self.model_name = model_name + self.prompt = prompt + self.pending_chunks: list[str] = [] + self.answer_text_buffer: list[tuple[int, str]] = [] + self.block_index = 0 + self.current_block: dict[str, object] = {"type": None, "index": None, "tool_call_id": None} + self.opened_tool_calls: set[str] = set() + + def ensure_message_start(self) -> None: + if not self.pending_chunks: + self.pending_chunks.append(_message_start_event(self.msg_id, self.model_name, self.prompt, "")) + + def close_current_block(self) -> None: + index = self.current_block.get("index") + if index is None: + return + self.pending_chunks.append(stream_presenter.anthropic_content_block_stop(index)) + self.current_block = {"type": None, "index": None, "tool_call_id": None} + + def open_textual_block(self, block_type: str) -> int: + current_type = self.current_block.get("type") + current_index = self.current_block.get("index") + if current_type == block_type and isinstance(current_index, int): + return current_index + self.close_current_block() + index = self.block_index + self.block_index += 1 + if block_type == "thinking": + content_block = {"type": "thinking", "thinking": ""} + else: + content_block = {"type": "text", "text": ""} + self.pending_chunks.append(stream_presenter.anthropic_content_block_start(index, content_block)) + self.current_block = {"type": block_type, "index": index, "tool_call_id": None} + return index + + def open_tool_block(self, tool_call_id: str, tool_name: str) -> int: + current_index = self.current_block.get("index") + if ( + self.current_block.get("type") == "tool_use" + and self.current_block.get("tool_call_id") == tool_call_id + and isinstance(current_index, int) + ): + return current_index + self.close_current_block() + index = self.block_index + self.block_index += 1 + self.pending_chunks.append( + f"event: content_block_start\ndata: {json.dumps({'type': 'content_block_start', 'index': index, 'content_block': {'type': 'tool_use', 'id': tool_call_id, 'name': tool_name, 'input': {}}}, ensure_ascii=False)}\n\n" + ) + self.current_block = {"type": "tool_use", "index": index, "tool_call_id": tool_call_id} + self.opened_tool_calls.add(tool_call_id) + return index + + def append_thinking_delta(self, text_chunk: str) -> None: + index = self.open_textual_block("thinking") + self.pending_chunks.append( + stream_presenter.anthropic_content_block_delta(index, {"type": "thinking_delta", "thinking": text_chunk}) + ) + + def buffer_answer_text(self, text_chunk: str) -> None: + index = self.open_textual_block("text") + self.answer_text_buffer.append((index, text_chunk)) + + def append_tool_delta(self, *, tool_call_id: str, tool_name: str, partial_json: str) -> None: + index = self.open_tool_block(tool_call_id, tool_name) + if partial_json: + self.pending_chunks.append( + stream_presenter.anthropic_content_block_delta(index, {"type": "input_json_delta", "partial_json": partial_json}) + ) + + def flush_answer_text(self) -> None: + if not self.answer_text_buffer: + return + for index, text_chunk in self.answer_text_buffer: + self.pending_chunks.append( + stream_presenter.anthropic_content_block_delta(index, {"type": "text_delta", "text": text_chunk}) + ) + self.answer_text_buffer = [] + + def clear_answer_text(self) -> None: + self.answer_text_buffer = [] + + +def _build_standard_request(req_data: dict) -> StandardRequest: + """使用 CLIProxy 进行协议转换""" + standard_request = CLIProxy.from_anthropic(req_data, client_profile=CLAUDE_CODE_OPENAI_PROFILE) + CLIProxy.log_conversion("anthropic", standard_request.response_model, len(standard_request.prompt), len(standard_request.tools)) + return standard_request + + +def _anthropic_usage(prompt: str, answer_text: str) -> dict[str, int]: + return {"input_tokens": len(prompt), "output_tokens": len(answer_text)} + + +def _message_start_event(msg_id: str, model_name: str, prompt: str, answer_text: str) -> str: + return stream_presenter.anthropic_message_start(msg_id, model_name, _anthropic_usage(prompt, answer_text)) + + +async def _run_anthropic_attempt( + *, + client: QwenClient, + standard_request: StandardRequest, + current_prompt: str, + history_messages: list[dict], + stream_attempt: int, + max_attempts: int, +): + update_request_context(stream_attempt=stream_attempt + 1) + execution = await collect_completion_run(client, standard_request, current_prompt) + retry = evaluate_retry_directive( + request=standard_request, + current_prompt=current_prompt, + history_messages=history_messages, + attempt_index=stream_attempt, + max_attempts=max_attempts, + state=execution.state, + allow_after_visible_output=True, + ) + return execution, retry + + +def _visible_answer_text_length(*, directive, execution, stream_state: _AnthropicStreamState | None = None) -> int: + if directive.stop_reason == "tool_use": + return 0 + if stream_state is not None: + return sum(len(text_chunk) for _, text_chunk in stream_state.answer_text_buffer) + return len(execution.state.answer_text) + + +async def _add_used_tokens_for_prompt(*, users_db, token: str, prompt_text: str, answer_text_length: int) -> None: + users = await users_db.get() + for user in users: + if user["id"] == token: + user["used_tokens"] += answer_text_length + len(prompt_text) + break + await users_db.save(users) + + +async def _reacquire_bound_account_if_needed(*, client: QwenClient, standard_request: StandardRequest) -> None: + preferred_email = getattr(standard_request, "bound_account_email", None) + if preferred_email: + standard_request.bound_account = await client.account_pool.acquire_wait_preferred(preferred_email, timeout=60) + else: + standard_request.bound_account = None + + +@router.post("/messages/count_tokens") +@router.post("/v1/messages/count_tokens") +@router.post("/anthropic/v1/messages/count_tokens") +async def anthropic_count_tokens(request: Request): + try: + req_data = await request.json() + except Exception: + raise HTTPException(400, {"error": {"message": "Invalid JSON body", "type": "invalid_request_error"}}) + prompt_result = messages_to_prompt(req_data, client_profile=CLAUDE_CODE_OPENAI_PROFILE) + base_tokens = count_tokens(prompt_result.prompt) + # Context Pressure Inflation: + # Claude Code 假设 context window=200K,到 ~80%(160K) 触发自动压缩。 + # 但 Qwen 实际上游 window 只有 ~150K,到 ~120K 时就开始挤压输出预算。 + # 虚增 input_tokens 1.35x 让 CC 提前触发压缩,避免爆 window。 + inflation = 1.35 + inflated = int(base_tokens * inflation) + return JSONResponse({"input_tokens": inflated}) + + +@router.post("/messages") +@router.post("/v1/messages") +@router.post("/anthropic/v1/messages") +async def anthropic_messages(request: Request): + app = request.app + users_db = app.state.users_db + client: QwenClient = app.state.qwen_client + + auth = await resolve_auth_context(request, users_db) + token = auth.token + + try: + req_data = await request.json() + except Exception: + raise HTTPException(400, {"error": {"message": "Invalid JSON body", "type": "invalid_request_error"}}) + + session_key = derive_session_key("anthropic", token, req_data) + original_history_messages = req_data.get("messages", []) + + async def prepare_locked_request(payload: dict) -> tuple[StandardRequest, dict, str, str, str, str]: + file_store = getattr(app.state, "file_store", None) + preprocessed = None + working_payload = payload + if file_store is not None: + preprocessed = await preprocess_attachments(working_payload, file_store, owner_token=token) + working_payload = preprocessed.payload + context_prepared = await prepare_context_attachments( + app=app, + payload=working_payload, + surface="anthropic", + auth_token=token, + client_profile=CLAUDE_CODE_OPENAI_PROFILE, + existing_attachments=(preprocessed.attachments if preprocessed is not None else None), + ) + working_payload = context_prepared["payload"] + standard_request = _build_standard_request(working_payload) + if preprocessed is not None: + standard_request.attachments = preprocessed.attachments + standard_request.uploaded_file_ids = preprocessed.uploaded_file_ids + standard_request.upstream_files = context_prepared["upstream_files"] + standard_request.session_key = context_prepared["session_key"] + standard_request.context_mode = context_prepared["context_mode"] + standard_request.bound_account_email = context_prepared["bound_account_email"] + standard_request.bound_account = context_prepared["bound_account"] + + session_plan = await plan_persistent_session_turn(app=app, request=standard_request, payload=working_payload, surface="anthropic") + if session_plan.enabled: + standard_request.persistent_session = True + standard_request.full_prompt = session_plan.full_prompt + standard_request.prompt = session_plan.prompt + standard_request.session_message_hashes = session_plan.current_hashes + standard_request.upstream_chat_id = session_plan.existing_chat_id if session_plan.reuse_chat else None + if standard_request.bound_account is None and session_plan.account_email: + standard_request.bound_account = await app.state.account_pool.acquire_wait_preferred(session_plan.account_email, timeout=60) + if standard_request.bound_account is not None: + standard_request.bound_account_email = standard_request.bound_account.email + elif standard_request.bound_account is not None and not standard_request.bound_account_email: + standard_request.bound_account_email = standard_request.bound_account.email + if standard_request.upstream_chat_id and standard_request.bound_account is None: + log_session_plan_reuse_cancelled( + request=standard_request, + planned_chat_id=session_plan.existing_chat_id, + reason="missing_bound_account", + ) + standard_request.upstream_chat_id = None + standard_request.prompt = standard_request.full_prompt or standard_request.prompt + + model_name = standard_request.response_model + qwen_model = standard_request.resolved_model + prompt = standard_request.prompt + msg_id = f"msg_{uuid.uuid4().hex[:12]}" + return standard_request, working_payload, model_name, qwen_model, prompt, msg_id + + with request_context(req_id=new_request_id(), surface="anthropic", requested_model=req_data.get("model", "claude-3-5-sonnet"), resolved_model="-", api_key=auth.token): + if request.headers.get("x-debug-session-key"): + pass + + if req_data.get("stream", False): + async def generate(): + async with app.state.session_locks.hold(session_key): + standard_request, effective_payload, model_name, qwen_model, prompt, msg_id = await prepare_locked_request(req_data) + update_request_context(requested_model=model_name, resolved_model=qwen_model) + log.info(f"[ANT] model={qwen_model}, stream={standard_request.stream}, tool_enabled={standard_request.tool_enabled}, tools={[t.get('name') for t in standard_request.tools]}, prompt_len={len(prompt)}") + history_messages = original_history_messages + current_prompt = prompt + max_attempts = request_max_attempts(standard_request) + for stream_attempt in range(max_attempts): + stream_state = _AnthropicStreamState(msg_id=msg_id, model_name=model_name, prompt=current_prompt) + try: + update_request_context(stream_attempt=stream_attempt + 1) + + async def on_delta(evt, text_chunk, _): + stream_state.ensure_message_start() + phase = evt.get("phase") + if text_chunk and phase in ("think", "thinking_summary"): + stream_state.append_thinking_delta(text_chunk) + return + if text_chunk and phase == "answer": + stream_state.buffer_answer_text(text_chunk) + return + if phase == "tool_call": + extra = evt.get("extra", {}) or {} + tool_call_id = extra.get("tool_call_id") + if tool_call_id is None: + tool_call_id = f"tc_idx_{extra.get('index', 0)}" + tool_name = extra.get("tool_name") + if not tool_name: + return + stream_state.append_tool_delta( + tool_call_id=str(tool_call_id), + tool_name=str(tool_name), + partial_json=evt.get("content", ""), + ) + + execution = await collect_completion_run_with_recovery( + client, + standard_request, + current_prompt, + capture_events=False, + on_delta=on_delta, + max_continuation=2, + warmup_chars=64, + guard_chars=96, + ) + retry = evaluate_retry_directive( + request=standard_request, + current_prompt=current_prompt, + history_messages=history_messages, + attempt_index=stream_attempt, + max_attempts=max_attempts, + state=execution.state, + allow_after_visible_output=True, + ) + if retry.retry: + reused_persistent_chat = bool(standard_request.persistent_session and standard_request.upstream_chat_id) + # 如果正在复用会话,重试时保留会话,避免删除后重建导致上下文丢失 + preserve_chat = reused_persistent_chat + await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat) + if reused_persistent_chat: + # 保留 upstream_chat_id,在同一会话中重试 + # standard_request.session_chat_invalidated = True + # standard_request.upstream_chat_id = None + current_prompt = build_retry_rebase_prompt(standard_request, reason=retry.reason) + else: + current_prompt = retry.next_prompt + await _reacquire_bound_account_if_needed(client=client, standard_request=standard_request) + continue + + if not stream_state.pending_chunks: + stream_state.pending_chunks.append(_message_start_event(msg_id, model_name, current_prompt, execution.state.answer_text)) + + stream_state.close_current_block() + directive = build_tool_directive(standard_request, execution.state) + if directive.stop_reason == "tool_use": + stream_state.clear_answer_text() + stream_state.current_block = {"type": None, "index": None, "tool_call_id": None} + else: + stream_state.flush_answer_text() + expected_tool_ids = { + block.get("id") + for block in directive.tool_blocks + if block.get("type") == "tool_use" and block.get("id") + } + for block in directive.tool_blocks: + if block.get("type") != "tool_use": + continue + tool_id = block.get("id") + if tool_id in stream_state.opened_tool_calls: + continue + index = stream_state.open_tool_block(str(tool_id), str(block.get("name", ""))) + stream_state.pending_chunks.append( + stream_presenter.anthropic_content_block_delta(index, {'type': 'input_json_delta', 'partial_json': json.dumps(block.get('input', {}), ensure_ascii=False)}) + ) + stream_state.close_current_block() + + visible_answer_length = _visible_answer_text_length( + directive=directive, + execution=execution, + stream_state=stream_state, + ) + stop_reason = "tool_use" if expected_tool_ids else "end_turn" + stream_state.pending_chunks.append(stream_presenter.anthropic_message_delta(stop_reason, visible_answer_length)) + stream_state.pending_chunks.append(stream_presenter.anthropic_message_stop()) + + await _add_used_tokens_for_prompt( + users_db=users_db, + token=token, + prompt_text=current_prompt, + answer_text_length=len(execution.state.answer_text), + ) + assistant_message = build_anthropic_assistant_history_message( + execution=execution, + request=standard_request, + directive=directive, + ) + await persist_session_turn( + app=app, + request=standard_request, + surface="anthropic", + execution=execution, + assistant_message=assistant_message, + ) + await cleanup_runtime_resources( + client, + execution.acc, + execution.chat_id, + preserve_chat=bool(standard_request.persistent_session), + ) + for chunk in stream_state.pending_chunks: + yield chunk + return + except HTTPException as he: + await clear_invalidated_session_chat(app=app, request=standard_request) + yield f"event: error\ndata: {json.dumps({'type': 'error', 'error': {'type': 'api_error', 'message': he.detail}}, ensure_ascii=False)}\n\n" + return + except Exception as e: + await clear_invalidated_session_chat(app=app, request=standard_request) + yield f"event: error\ndata: {json.dumps({'type': 'error', 'error': {'type': 'api_error', 'message': str(e)}}, ensure_ascii=False)}\n\n" + return + + return StreamingResponse( + generate(), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + + async with app.state.session_locks.hold(session_key): + standard_request, effective_payload, model_name, qwen_model, prompt, msg_id = await prepare_locked_request(req_data) + update_request_context(requested_model=model_name, resolved_model=qwen_model) + log.info(f"[ANT] model={qwen_model}, stream={standard_request.stream}, tool_enabled={standard_request.tool_enabled}, tools={[t.get('name') for t in standard_request.tools]}, prompt_len={len(prompt)}") + history_messages = original_history_messages + current_prompt = prompt + max_attempts = request_max_attempts(standard_request) + for stream_attempt in range(max_attempts): + try: + execution, retry = await _run_anthropic_attempt( + client=client, + standard_request=standard_request, + current_prompt=current_prompt, + history_messages=history_messages, + stream_attempt=stream_attempt, + max_attempts=max_attempts, + ) + if retry.retry: + reused_persistent_chat = bool(standard_request.persistent_session and standard_request.upstream_chat_id) + # 如果正在复用会话,重试时保留会话,避免删除后重建导致上下文丢失 + preserve_chat = reused_persistent_chat + await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat) + if reused_persistent_chat: + # 保留 upstream_chat_id,在同一会话中重试 + # standard_request.session_chat_invalidated = True + # standard_request.upstream_chat_id = None + current_prompt = build_retry_rebase_prompt(standard_request, reason=retry.reason) + else: + current_prompt = retry.next_prompt + await _reacquire_bound_account_if_needed(client=client, standard_request=standard_request) + continue + + directive = build_tool_directive(standard_request, execution.state) + content_blocks: list[dict] = [] + if execution.state.reasoning_text: + content_blocks.append({"type": "thinking", "thinking": execution.state.reasoning_text}) + content_blocks.extend(directive.tool_blocks) + + await _add_used_tokens_for_prompt( + users_db=users_db, + token=token, + prompt_text=current_prompt, + answer_text_length=len(execution.state.answer_text), + ) + assistant_message = build_anthropic_assistant_history_message( + execution=execution, + request=standard_request, + directive=directive, + ) + await persist_session_turn( + app=app, + request=standard_request, + surface="anthropic", + execution=execution, + assistant_message=assistant_message, + ) + await cleanup_runtime_resources( + client, + execution.acc, + execution.chat_id, + preserve_chat=bool(standard_request.persistent_session), + ) + + return JSONResponse( + { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": model_name, + "content": content_blocks, + "stop_reason": directive.stop_reason, + "stop_sequence": None, + "usage": _anthropic_usage(current_prompt, execution.state.answer_text), + } + ) + except Exception as e: + if stream_attempt == max_attempts - 1: + await clear_invalidated_session_chat(app=app, request=standard_request) + raise HTTPException(status_code=500, detail=str(e)) diff --git a/backend/api/embeddings.py b/backend/api/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..bd21ffa7dcc1d589f7e98e69547fab4677432caf --- /dev/null +++ b/backend/api/embeddings.py @@ -0,0 +1,90 @@ +from fastapi import APIRouter, Request, HTTPException +import json +import uuid +import logging +from backend.services.token_calc import count_tokens + +log = logging.getLogger("qwen2api.embeddings") +router = APIRouter() + +@router.post("/embeddings") +@router.post("/v1/embeddings") +async def create_embeddings(request: Request): + """ + Embeddings 模拟/转发接口。 + 通义千问 Web 版没有原生的 Embeddings 接口。 + 为了兼容部分客户端强制验证 Embeddings 的情况(如 OpenWebUI 的某些场景), + 这里提供基于 Tiktoken 和 Hash 的模拟响应,或配置专门的小模型转发。 + 目前实现为模拟返回。 + """ + app = request.app + users_db = app.state.users_db + + # 鉴权 (完全复原单文件逻辑) + auth_header = request.headers.get("Authorization", "") + token = auth_header[7:].strip() if auth_header.startswith("Bearer ") else "" + + if not token: + token = request.headers.get("x-api-key", "").strip() + if not token: + token = request.query_params.get("key", "").strip() or request.query_params.get("api_key", "").strip() + + from backend.core.config import API_KEYS, settings + admin_k = settings.ADMIN_KEY + + if API_KEYS: + if token != admin_k and token not in API_KEYS and not token: + raise HTTPException(status_code=401, detail="Invalid API Key") + + users = await users_db.get() + user = next((u for u in users if u["id"] == token), None) + if user and user.get("quota", 0) <= user.get("used_tokens", 0): + raise HTTPException(status_code=402, detail="Quota Exceeded") + + body = await request.json() + model = body.get("model", "text-embedding-ada-002") + input_text = body.get("input", "") + + if isinstance(input_text, str): + input_list = [input_text] + else: + input_list = input_text + + data = [] + total_tokens = 0 + + for i, text in enumerate(input_list): + tokens = count_tokens(text) + total_tokens += tokens + + # 模拟生成 1536 维的特征向量 + # 基于文本 hash 的简单确定性伪随机向量,保证同一文本结果一致 + import hashlib + h = hashlib.sha256(text.encode('utf-8')).hexdigest() + base_val = int(h[:8], 16) / 0xffffffff + vector = [(base_val * (j % 10) / 10.0) - 0.5 for j in range(1536)] + + data.append({ + "object": "embedding", + "embedding": vector, + "index": i + }) + + usage = { + "prompt_tokens": total_tokens, + "total_tokens": total_tokens + } + + # 异步扣除 Token + for u in users: + if u["id"] == token: + u["used_tokens"] += usage["total_tokens"] + break + await users_db.save(users) + + return { + "object": "list", + "data": data, + "model": model, + "usage": usage + } diff --git a/backend/api/files_api.py b/backend/api/files_api.py new file mode 100644 index 0000000000000000000000000000000000000000..a684477e8a29115c7c4938413f6bce5d8b97353d --- /dev/null +++ b/backend/api/files_api.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import os +from pathlib import Path + +from fastapi import APIRouter, File, HTTPException, Request, UploadFile +from fastapi.responses import JSONResponse + +from backend.core.config import settings +from backend.services.auth_quota import resolve_auth_context + +router = APIRouter() + + +def _allowed_exts() -> set[str]: + return {item.strip().lower() for item in settings.CONTEXT_ALLOWED_USER_EXTS.split(",") if item.strip()} + + +def _validate_upload(filename: str) -> None: + ext = Path(filename).suffix.lower().lstrip(".") + if not ext or ext not in _allowed_exts(): + raise HTTPException(status_code=400, detail=f"Unsupported file extension: {ext or 'none'}") + + +@router.post("/api/files/upload") +@router.post("/v1/files") +async def upload_file(request: Request, file: UploadFile = File(...)): + app = request.app + users_db = app.state.users_db + auth = await resolve_auth_context(request, users_db) + token = auth.token + + _validate_upload(file.filename or "") + raw = await file.read() + if not raw: + raise HTTPException(status_code=400, detail="Empty file") + + file_store = app.state.file_store + meta = await file_store.save_bytes( + file.filename or "upload.bin", + file.content_type or "application/octet-stream", + raw, + "upload", + owner_token=token, + ) + return JSONResponse({ + "id": meta["id"], + "object": "file", + "filename": meta["filename"], + "bytes": meta["size"], + "content_type": meta["content_type"], + "created_at": meta["created_at"], + "content_block": { + "type": "input_file", + "file_id": meta["id"], + "filename": meta["filename"], + "mime_type": meta["content_type"], + }, + }) + + +@router.delete("/api/files/{file_id}") +@router.delete("/v1/files/{file_id}") +async def delete_file(request: Request, file_id: str): + app = request.app + users_db = app.state.users_db + auth = await resolve_auth_context(request, users_db) + token = auth.token + + file_store = app.state.file_store + meta = await file_store.get(file_id) + if meta is None: + raise HTTPException(status_code=404, detail="File not found") + if meta.get("owner_token") and meta.get("owner_token") != token: + raise HTTPException(status_code=403, detail="Forbidden") + await file_store.delete(file_id) + return {"deleted": True, "id": file_id} diff --git a/backend/api/gemini.py b/backend/api/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..12c512a25117e50f6c63cdfe68f4c98e08b0a1c2 --- /dev/null +++ b/backend/api/gemini.py @@ -0,0 +1,145 @@ +from fastapi import APIRouter, Request, HTTPException +from fastapi.responses import JSONResponse, StreamingResponse +import asyncio +import json +import logging +from typing import Any + +from backend.adapter.standard_request import StandardRequest +from backend.adapter.cli_proxy import CLIProxy +from backend.core.config import resolve_model +from backend.core.request_logging import new_request_id, request_context, update_request_context +from backend.runtime import stream_presenter +from backend.runtime.execution import collect_completion_run, cleanup_runtime_resources +from backend.services.auth_quota import resolve_auth_context +from backend.services.token_calc import calculate_usage + +log = logging.getLogger("qwen2api.gemini") +router = APIRouter() + +GEMINI_STREAM_MEDIA_TYPE = "application/json" + + +def _build_standard_request(model: str, body: dict, *, stream: bool | None = None) -> StandardRequest: + """使用 CLIProxy 进行协议转换""" + standard_request = CLIProxy.from_gemini(model, body, stream=stream) + CLIProxy.log_conversion("gemini", standard_request.response_model, len(standard_request.prompt), len(standard_request.tools)) + return standard_request + + +def _gemini_chunk_payload(text: str) -> dict[str, Any]: + return { + "candidates": [ + { + "content": { + "parts": [{"text": text}], + "role": "model", + } + } + ] + } + + +async def _load_and_validate_request(request: Request, model: str, *, force_stream: bool | None = None): + app = request.app + users_db = app.state.users_db + client = app.state.qwen_client + + auth = await resolve_auth_context(request, users_db) + token = auth.token + + body = await request.json() + standard_request = _build_standard_request(model, body, stream=force_stream) + update_request_context(resolved_model=standard_request.resolved_model) + return users_db, client, token, standard_request + + +@router.post("/v1beta/models/{model}:generateContent") +@router.post("/v1/models/{model}:generateContent") +@router.post("/models/{model}:generateContent") +async def gemini_generate_content(model: str, request: Request): + with request_context(req_id=new_request_id(), surface="gemini", requested_model=model): + users_db, client, token, standard_request = await _load_and_validate_request(request, model, force_stream=False) + content = standard_request.prompt + log.info(f"[Gemini] route=generateContent model={standard_request.resolved_model}, stream={standard_request.stream}, prompt_len={len(content)}") + + try: + execution = await collect_completion_run(client, standard_request, content) + except Exception as e: + log.error(f"Gemini proxy failed: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + usage = calculate_usage(content, execution.state.answer_text) + users = await users_db.get() + for u in users: + if u["id"] == token: + u["used_tokens"] += usage["total_tokens"] + break + await users_db.save(users) + await cleanup_runtime_resources(client, execution.acc, execution.chat_id) + + log.info(f"[Gemini] Request complete. Generated {len(execution.state.answer_text)} characters.") + return JSONResponse( + { + "candidates": [ + { + "content": { + "parts": [{"text": execution.state.answer_text}], + "role": "model", + } + } + ] + } + ) + + +@router.post("/v1beta/models/{model}:streamGenerateContent") +@router.post("/v1/models/{model}:streamGenerateContent") +@router.post("/models/{model}:streamGenerateContent") +async def gemini_stream_generate_content(model: str, request: Request): + with request_context(req_id=new_request_id(), surface="gemini", requested_model=model): + users_db, client, token, standard_request = await _load_and_validate_request(request, model, force_stream=True) + content = standard_request.prompt + log.info(f"[Gemini] route=streamGenerateContent model={standard_request.resolved_model}, stream={standard_request.stream}, prompt_len={len(content)}") + + async def generate(): + queue: asyncio.Queue[str | None] = asyncio.Queue() + + async def on_delta(evt, text_chunk, _): + if text_chunk and evt.get("phase") == "answer": + await queue.put(stream_presenter.gemini_text_chunk(text_chunk)) + + async def runner(): + execution = None + try: + execution = await collect_completion_run( + client, + standard_request, + content, + capture_events=False, + on_delta=on_delta, + ) + + usage = calculate_usage(content, execution.state.answer_text) + users = await users_db.get() + for u in users: + if u["id"] == token: + u["used_tokens"] += usage["total_tokens"] + break + await users_db.save(users) + await cleanup_runtime_resources(client, execution.acc, execution.chat_id) + log.info(f"[Gemini] Request complete. Generated {len(execution.state.answer_text)} characters.") + except Exception as e: + await queue.put(json.dumps({"error": str(e)}) + "\n") + finally: + await queue.put(None) + + task = asyncio.create_task(runner()) + while True: + chunk = await queue.get() + if chunk is None: + break + yield chunk + await task + + return StreamingResponse(generate(), media_type=GEMINI_STREAM_MEDIA_TYPE) diff --git a/backend/api/images.py b/backend/api/images.py new file mode 100644 index 0000000000000000000000000000000000000000..f81a801085df5bfca94b920c822ad0a11f96a8bc --- /dev/null +++ b/backend/api/images.py @@ -0,0 +1,599 @@ +""" +图片生成接口 — 兼容 OpenAI /v1/images/generations 与 /v1/images/edits。 + +- generations: 文生图 t2i +- edits: 图生图 i2i(参考角色/场景 sheet 生成分镜,供 ArcReel 使用) + +优先走与视频相同的 HTTP 直连 complete_once, +避免依赖 Playwright 浏览器路径(易超时)。 +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import logging +import mimetypes +import os +import re +import time +from typing import Any + +import httpx +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse + +from backend.services.qwen_client import QwenClient + +log = logging.getLogger("qwen2api.images") +router = APIRouter() + +# 注意:chat.qwen.ai 网页侧没有独立的“专用生图模型 ID”, +# t2i 实际是聊天模型挂载 image_gen/t2i 能力。默认改用更高档模型。 +DEFAULT_IMAGE_MODEL = "qwen3.7-max" + +IMAGE_MODEL_MAP = { + "dall-e-3": "qwen3.7-max", + "dall-e-2": "qwen3.6-plus", + "qwen-image": "qwen3.7-max", + "qwen-image-plus": "qwen3.7-max", + "qwen-image-max": "qwen3.8-max-preview", + "qwen-image-turbo": "qwen3.6-plus", + "qwen3.6-plus": "qwen3.6-plus", + "qwen3.6-max-preview": "qwen3.6-max-preview", + "qwen3.7-plus": "qwen3.7-plus", + "qwen3.7-max": "qwen3.7-max", + "qwen3.8-max-preview": "qwen3.8-max-preview", + "qwen3.8": "qwen3.8-max-preview", +} + +HTTP_URL_RE = re.compile(r"https?://[^\s\"'<>)]+", re.IGNORECASE) +IMAGE_EXT_RE = re.compile(r"\.(?:jpg|jpeg|png|webp|gif)(?:[?#]|$)", re.IGNORECASE) + + +def _extract_image_urls(value: Any) -> list[str]: + urls: list[str] = [] + + def walk(v: Any, key_hint: str = ""): + if v is None: + return + if isinstance(v, str): + # markdown images + for u in re.findall(r"!\[.*?\]\((https?://[^\s\)]+)\)", v): + urls.append(u.rstrip(").,;")) + for u in HTTP_URL_RE.findall(v): + u2 = u.rstrip(".,;)\"'>") + low = u2.lower() + hint = key_hint.lower() + if IMAGE_EXT_RE.search(low) or any(x in low for x in ("cdn.qwenlm.ai", "alicdn.com", "/image", "img")): + if not any(x in low for x in (".mp4", ".webm", ".mov")): + urls.append(u2) + elif any(x in hint for x in ("image", "url", "src", "thumb")) and u2.startswith("http"): + if not any(x in low for x in (".mp4", ".webm", ".mov")): + urls.append(u2) + return + if isinstance(v, list): + for item in v: + walk(item, key_hint) + return + if isinstance(v, dict): + for k, item in v.items(): + walk(item, str(k)) + + walk(value) + + seen: set[str] = set() + out: list[str] = [] + for u in urls: + if u not in seen: + seen.add(u) + out.append(u) + return out + + +def _extract_task_ids(value: Any) -> list[str]: + ids: list[str] = [] + + def walk(v: Any): + if v is None: + return + if isinstance(v, list): + for item in v: + walk(item) + return + if isinstance(v, dict): + for k, item in v.items(): + if k in {"task_id", "taskId"} and isinstance(item, str) and item.strip(): + ids.append(item.strip()) + else: + walk(item) + + walk(value) + # de-dupe + seen: set[str] = set() + out: list[str] = [] + for i in ids: + if i not in seen: + seen.add(i) + out.append(i) + return out + + +def _resolve_image_model(requested: str | None) -> str: + if not requested: + return DEFAULT_IMAGE_MODEL + return IMAGE_MODEL_MAP.get(requested, DEFAULT_IMAGE_MODEL) + + +def _get_token(request: Request) -> str: + auth = request.headers.get("Authorization", "") + if auth.startswith("Bearer "): + return auth[7:].strip() + return request.headers.get("x-api-key", "").strip() + + +def _build_image_prompt(prompt: str) -> str: + return ( + "Generate an image now. Return an accessible image URL if possible. " + "Do not only describe the image in words.\n\n" + f"User request: {prompt}" + ) + + +async def _poll_image_task(client: QwenClient, token: str, task_id: str, *, timeout_seconds: int = 300) -> dict: + started = time.monotonic() + last: dict = {} + while time.monotonic() - started < timeout_seconds: + task_status = await client.get_task_status(token, task_id) + last = task_status if isinstance(task_status, dict) else {} + data = last.get("data") if isinstance(last.get("data"), dict) else last + state = str((data or {}).get("task_status") or (data or {}).get("status") or "").lower() + log.info("[T2I] task_id=%s status=%s", task_id, state) + if state == "success": + return last + if state not in {"running", "pending", "queued", "created", "processing", ""}: + raise HTTPException(status_code=500, detail={"message": "Image task failed", "task_status": data}) + await asyncio.sleep(5) + raise HTTPException(status_code=504, detail={"message": "Image task timed out", "task_id": task_id, "last_status": last}) + + +@router.post("/v1/images/generations") +@router.post("/images/generations") +async def create_image(request: Request): + from backend.core.config import API_KEYS, settings + + client: QwenClient = request.app.state.qwen_client + + token = _get_token(request) + if API_KEYS: + if token != settings.ADMIN_KEY and token not in API_KEYS: + raise HTTPException(status_code=401, detail="Invalid API Key") + + try: + body = await request.json() + except Exception: + raise HTTPException(status_code=400, detail="Invalid JSON body") + + prompt: str = str(body.get("prompt", "")).strip() + if not prompt: + raise HTTPException(status_code=400, detail="prompt is required") + + n: int = min(max(int(body.get("n", 1)), 1), 4) + model = _resolve_image_model(body.get("model")) + size = str(body.get("size", "")).strip() or None + + log.info("[T2I] model=%s n=%s size=%s prompt=%r", model, n, size, prompt[:100]) + + acc = None + chat_id = None + try: + prompt_text = _build_image_prompt(prompt) + + # 1) Prefer same HTTP path as videos: create_chat(t2i) + complete_once + if client.account_pool is None: + raise HTTPException(status_code=500, detail="No upstream account pool configured") + + acc = await client.account_pool.acquire_wait(timeout=30) + if acc is None: + raise HTTPException(status_code=503, detail="No available upstream accounts") + + # Try t2i first; some deployments may only honor image mode via t2i chat_type + chat_type = "t2i" + try: + chat_id = await client.create_chat(acc.token, model, chat_type=chat_type) + except Exception as e: + log.warning("[T2I] create_chat t2i failed (%s), fallback t2t", e) + chat_type = "t2t" + chat_id = await client.create_chat(acc.token, model, chat_type=chat_type) + + log.info("[T2I] chat_id=%s account=%s chat_type=%s", chat_id, getattr(acc, "email", ""), chat_type) + + completion = await client.complete_once( + acc.token, + chat_id, + model, + prompt_text, + has_custom_tools=False, + chat_type=chat_type, + size=size, + ) + + search_payload: list[Any] = [completion] + try: + chat_detail = await client.get_chat(acc.token, chat_id) + search_payload.append(chat_detail) + except Exception as chat_error: + log.warning("[T2I] get_chat failed: %s", chat_error) + + task_ids = _extract_task_ids(search_payload) + if task_ids: + log.info("[T2I] task IDs: %s", task_ids) + task_result = await _poll_image_task(client, acc.token, task_ids[0]) + search_payload.append(task_result) + + image_urls = _extract_image_urls(search_payload) + log.info("[T2I] extracted %s image URLs: %s", len(image_urls), image_urls[:5]) + + if not image_urls: + # fallback: old stream path (may need playwright) + log.warning("[T2I] HTTP path got no image URL, trying stream fallback") + event_payloads: list[str] = [] + async for item in client.chat_stream_events_with_retry(model, prompt_text, has_custom_tools=False): + if item.get("type") == "event": + event_payloads.append(json.dumps(item.get("event", {}), ensure_ascii=False)) + image_urls = _extract_image_urls("\n".join(event_payloads)) + + if not image_urls: + debug_path = ( + __import__("os").path.join( + __import__("os").path.dirname(__import__("os").path.dirname(__import__("os").path.dirname(__file__))), + "logs", + "t2i-last-debug.json", + ) + ) + try: + with open(debug_path, "w", encoding="utf-8") as f: + json.dump({"completion": completion, "search": search_payload}, f, ensure_ascii=False, indent=2) + except Exception: + pass + raise HTTPException(status_code=500, detail="Image generation succeeded but no URL found") + + # 默认返回 b64_json:ArcReel 等 Docker 容器常无法稳定下载 cdn.qwenlm.ai, + # 由宿主机网关下载后转 base64,可避免容器二次拉 CDN 失败。 + response_format = str(body.get("response_format", "b64_json") or "b64_json").lower() + selected = image_urls[:n] + data: list[dict[str, Any]] = [] + if response_format == "url": + data = [{"url": url, "revised_prompt": prompt} for url in selected] + else: + async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as http: + for url in selected: + item: dict[str, Any] = {"url": url, "revised_prompt": prompt} + try: + resp = await http.get(url) + resp.raise_for_status() + item["b64_json"] = base64.b64encode(resp.content).decode("ascii") + except Exception as dl_err: + log.warning("[T2I] download for b64 failed url=%s err=%s", url[:120], dl_err) + data.append(item) + if not any(x.get("b64_json") for x in data): + # 全部下载失败时退回纯 URL,至少不让接口 500 + log.warning("[T2I] all b64 downloads failed, fallback to url-only response") + return JSONResponse({"created": int(time.time()), "data": data}) + + except HTTPException: + raise + except Exception as e: + log.error("[T2I] generation failed: %s", e) + raise HTTPException(status_code=500, detail=str(e)) + finally: + if acc is not None: + try: + client.account_pool.release(acc) + except Exception: + pass + if chat_id: + asyncio.create_task(client.delete_chat(acc.token, chat_id)) + + +def _build_i2i_prompt(prompt: str) -> str: + return ( + "Image-to-image edit / storyboard frame generation. " + "STRICTLY keep the same character identity, face, hairstyle, clothing colors, " + "art style and overall look from the attached reference image(s). " + "Only change pose, camera angle, composition and scene details as requested. " + "Generate an image now and return an accessible image URL if possible. " + "Do not only describe the image in words.\n\n" + f"User request: {prompt}" + ) + + +async def _upload_i2i_refs(client: QwenClient, acc: Any, raw_files: list[tuple[bytes, str, str]]) -> list[dict]: + """Upload local image bytes and build vision file refs for complete_once(files=...).""" + from backend.core.config import settings + from backend.services.upstream_file_uploader import UpstreamFileUploader + + uploader = UpstreamFileUploader(client, settings) + out: list[dict] = [] + tmp_dir = os.path.join( + os.path.dirname(os.path.dirname(os.path.dirname(__file__))), + "logs", + "image_refs", + ) + os.makedirs(tmp_dir, exist_ok=True) + + for idx, (raw, content_type, filename) in enumerate(raw_files[:4]): + local_path = os.path.join(tmp_dir, f"{int(time.time())}_{idx}_{filename}") + with open(local_path, "wb") as f: + f.write(raw) + meta = { + "filename": filename, + "path": local_path, + "content_type": content_type, + "size": len(raw), + } + remote = await uploader.upload_local_file(acc, meta) + ref = remote.get("remote_ref") + put_url = "" + if isinstance(ref, dict): + put_url = str(ref.get("url") or "") + if not put_url: + put_url = str(remote.get("url") or "") + + vision_ref: dict[str, Any] = { + "type": "image", + "name": filename, + "file_type": content_type if content_type.startswith("image/") else "image/png", + "showType": "image", + "status": "uploaded", + "file_class": "vision", + "url": put_url, + } + if isinstance(ref, dict): + if ref.get("id"): + vision_ref["id"] = ref.get("id") + if isinstance(ref.get("file"), dict) and ref["file"].get("id"): + vision_ref["file"] = ref["file"] + for k in ("itemId", "uploadTaskId", "size", "greenNet", "progress", "error", "collection_name"): + if k in ref and k not in vision_ref: + vision_ref[k] = ref[k] + if not vision_ref.get("url"): + log.warning("[I2I] upload missing url, remote=%s", remote) + out.append(vision_ref) + log.info( + "[I2I] uploaded ref name=%s url=%s", + filename, + (vision_ref.get("url") or "")[:120], + ) + return out + + +async def _pack_image_response( + image_urls: list[str], + *, + prompt: str, + n: int, + response_format: str, +) -> JSONResponse: + selected = image_urls[:n] + data: list[dict[str, Any]] = [] + if response_format == "url": + data = [{"url": url, "revised_prompt": prompt} for url in selected] + else: + async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as http: + for url in selected: + item: dict[str, Any] = {"url": url, "revised_prompt": prompt} + try: + resp = await http.get(url) + resp.raise_for_status() + item["b64_json"] = base64.b64encode(resp.content).decode("ascii") + except Exception as dl_err: + log.warning("[I2I] download for b64 failed url=%s err=%s", url[:120], dl_err) + data.append(item) + if not any(x.get("b64_json") for x in data): + log.warning("[I2I] all b64 downloads failed, fallback to url-only response") + return JSONResponse({"created": int(time.time()), "data": data}) + + +@router.post("/v1/images/edits") +@router.post("/images/edits") +async def edit_image(request: Request): + """OpenAI-compatible image edits (i2i). + + Accepts multipart form (OpenAI SDK style) or JSON with image/images fields. + Uses Qwen vision + t2i tool path with attached reference image(s). + """ + from backend.core.config import API_KEYS, settings + + client: QwenClient = request.app.state.qwen_client + token = _get_token(request) + if API_KEYS: + if token != settings.ADMIN_KEY and token not in API_KEYS: + raise HTTPException(status_code=401, detail="Invalid API Key") + + content_type = (request.headers.get("content-type") or "").lower() + raw_files: list[tuple[bytes, str, str]] = [] + prompt = "" + model_name: str | None = None + n = 1 + size = None + response_format = "b64_json" + + if "multipart/form-data" in content_type or "application/x-www-form-urlencoded" in content_type: + form = await request.form() + prompt = str(form.get("prompt") or "").strip() + model_name = str(form.get("model") or "") or None + try: + n = min(max(int(form.get("n") or 1), 1), 4) + except Exception: + n = 1 + size = str(form.get("size") or "").strip() or None + response_format = str(form.get("response_format") or "b64_json").lower() + + # OpenAI SDK may send image / image[] / image[0] + candidates: list[Any] = [] + for key in form.keys(): + kl = key.lower() + if kl == "image" or kl.startswith("image[") or kl.startswith("image_") or kl in {"mask"}: + if kl == "mask": + continue + val = form.getlist(key) if hasattr(form, "getlist") else [form.get(key)] + candidates.extend(val) + # also single get + if not candidates and form.get("image") is not None: + candidates = [form.get("image")] + + for item in candidates: + if item is None: + continue + if hasattr(item, "read"): + raw = await item.read() + filename = getattr(item, "filename", None) or "ref.png" + ctype = getattr(item, "content_type", None) or mimetypes.guess_type(filename)[0] or "image/png" + if raw: + raw_files.append((raw, ctype, os.path.basename(filename) or "ref.png")) + elif isinstance(item, (bytes, bytearray)): + raw_files.append((bytes(item), "image/png", "ref.png")) + elif isinstance(item, str) and item.strip(): + # data url or path unlikely in multipart text; skip + pass + else: + try: + body = await request.json() + except Exception: + raise HTTPException(status_code=400, detail="Invalid JSON body; use multipart or JSON") + prompt = str(body.get("prompt") or "").strip() + model_name = body.get("model") + try: + n = min(max(int(body.get("n", 1)), 1), 4) + except Exception: + n = 1 + size = str(body.get("size") or "").strip() or None + response_format = str(body.get("response_format") or "b64_json").lower() + + def _add_str_image(val: str): + v = val.strip() + if not v: + return + if v.startswith("data:"): + header, b64 = v.split(",", 1) + ctype = "image/png" + if ";" in header: + ctype = header[5:].split(";")[0] or ctype + raw = base64.b64decode(b64) + ext = mimetypes.guess_extension(ctype) or ".png" + raw_files.append((raw, ctype, f"ref{ext}")) + elif v.startswith("http://") or v.startswith("https://"): + import urllib.request + + req = urllib.request.Request(v, headers={"User-Agent": "qwen2api-i2i/1.0"}) + with urllib.request.urlopen(req, timeout=60) as resp: + raw = resp.read() + ctype = resp.headers.get("Content-Type") or "image/png" + ext = mimetypes.guess_extension(ctype.split(";")[0].strip()) or ".png" + raw_files.append((raw, ctype.split(";")[0].strip(), f"ref{ext}")) + elif os.path.exists(v): + raw = open(v, "rb").read() + ctype = mimetypes.guess_type(v)[0] or "image/png" + raw_files.append((raw, ctype, os.path.basename(v) or "ref.png")) + + for key in ("image", "image_url", "reference_image", "ref_image"): + val = body.get(key) + if isinstance(val, str): + _add_str_image(val) + for key in ("images", "image_urls", "reference_images"): + val = body.get(key) + if isinstance(val, list): + for item in val: + if isinstance(item, str): + _add_str_image(item) + elif isinstance(item, dict): + u = item.get("url") or item.get("image_url") or item.get("b64_json") or item.get("data") + if isinstance(u, str): + if item.get("b64_json") and not u.startswith("data:"): + _add_str_image("data:image/png;base64," + u) + else: + _add_str_image(u) + + if not prompt: + raise HTTPException(status_code=400, detail="prompt is required") + if not raw_files: + raise HTTPException(status_code=400, detail="image is required for edits/i2i") + + model = _resolve_image_model(model_name) + log.info("[I2I] model=%s n=%s refs=%s prompt=%r", model, n, len(raw_files), prompt[:100]) + + acc = None + chat_id = None + try: + if client.account_pool is None: + raise HTTPException(status_code=500, detail="No upstream account pool configured") + acc = await client.account_pool.acquire_wait(timeout=30) + if acc is None: + raise HTTPException(status_code=503, detail="No available upstream accounts") + + files = await _upload_i2i_refs(client, acc, raw_files) + if not files or not any(f.get("url") for f in files): + raise HTTPException(status_code=500, detail="Failed to upload reference image(s) to upstream") + + prompt_text = _build_i2i_prompt(prompt) + # 网页侧图生图:带 vision 参考图的 t2i / t2t 会话 + chat_type = "t2i" + try: + chat_id = await client.create_chat(acc.token, model, chat_type=chat_type) + except Exception as e: + log.warning("[I2I] create_chat t2i failed (%s), fallback t2t", e) + chat_type = "t2t" + chat_id = await client.create_chat(acc.token, model, chat_type=chat_type) + + log.info("[I2I] chat_id=%s account=%s chat_type=%s files=%s", chat_id, getattr(acc, "email", ""), chat_type, len(files)) + + completion = await client.complete_once( + acc.token, + chat_id, + model, + prompt_text, + has_custom_tools=False, + files=files, + chat_type=chat_type, + size=size, + ) + + search_payload: list[Any] = [completion] + try: + chat_detail = await client.get_chat(acc.token, chat_id) + search_payload.append(chat_detail) + except Exception as chat_error: + log.warning("[I2I] get_chat failed: %s", chat_error) + + task_ids = _extract_task_ids(search_payload) + if task_ids: + log.info("[I2I] task IDs: %s", task_ids) + task_result = await _poll_image_task(client, acc.token, task_ids[0]) + search_payload.append(task_result) + + image_urls = _extract_image_urls(search_payload) + log.info("[I2I] extracted %s image URLs: %s", len(image_urls), image_urls[:5]) + if not image_urls: + raise HTTPException(status_code=500, detail="Image edit succeeded but no URL found") + + return await _pack_image_response( + image_urls, + prompt=prompt, + n=n, + response_format=response_format, + ) + except HTTPException: + raise + except Exception as e: + log.error("[I2I] edit failed: %s", e) + raise HTTPException(status_code=500, detail=str(e)) + finally: + if acc is not None: + try: + client.account_pool.release(acc) + except Exception: + pass + if chat_id: + asyncio.create_task(client.delete_chat(acc.token, chat_id)) diff --git a/backend/api/models.py b/backend/api/models.py new file mode 100644 index 0000000000000000000000000000000000000000..ac7ec40550ccb1c4f04573725ab22e95030f99a2 --- /dev/null +++ b/backend/api/models.py @@ -0,0 +1,59 @@ +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse + +from backend.core.config import MODEL_MAP, resolve_model +from backend.services.auth_quota import resolve_auth_context +from backend.services.qwen_client import QwenClient + +router = APIRouter() + + +def _build_model_list_payload() -> dict: + seen: set[str] = set() + data: list[dict] = [] + for model_id in MODEL_MAP: + if model_id in seen: + continue + seen.add(model_id) + data.append({"id": model_id, "object": "model", "owned_by": "qwen2api"}) + return {"object": "list", "data": data} + + +@router.get("/v1/models") +async def list_models(request: Request): + app = request.app + users_db = app.state.users_db + client: QwenClient = app.state.qwen_client + + # 鉴权(只校验客户端 API KEY,不把它当 Qwen token 用) + await resolve_auth_context(request, users_db) + + # 从账号池拿合法 Qwen token 调上游 /api/models,带 5min 缓存 + upstream_models = await client.list_models_from_pool() + + if upstream_models: + data = [] + for item in upstream_models: + if not isinstance(item, dict): + continue + model_id = item.get("id") or item.get("model") or item.get("name") + if not model_id: + continue + data.append({ + "id": model_id, + "object": "model", + "owned_by": item.get("owned_by", "qwen"), + "created": item.get("created_at") or 0, + }) + return JSONResponse({"object": "list", "data": data}) + + # 上游不可用时才回退到静态 MODEL_MAP(包含 gpt-4o/claude 等别名) + return JSONResponse(_build_model_list_payload()) + + +@router.get("/v1/models/{model_id}") +async def get_model(model_id: str): + resolved = resolve_model(model_id) + if resolved == model_id and model_id not in MODEL_MAP: + raise HTTPException(status_code=404, detail={"error": {"message": f"Model '{model_id}' not found", "type": "invalid_request_error"}}) + return JSONResponse({"id": model_id, "object": "model", "owned_by": "qwen2api", "resolved_model": resolved}) diff --git a/backend/api/probes.py b/backend/api/probes.py new file mode 100644 index 0000000000000000000000000000000000000000..797583652108675de6fa12ba81c86ab74578ae46 --- /dev/null +++ b/backend/api/probes.py @@ -0,0 +1,41 @@ +from fastapi import APIRouter, Request, Depends, HTTPException +from backend.api.admin import verify_admin +from backend.core.database import AsyncJsonDB + +router = APIRouter() + + +@router.get("/healthz") +async def healthz(): + return {"status": "ok"} + + +@router.get("/readyz") +async def readyz(request: Request): + required_state = ( + "accounts_db", + "users_db", + "captures_db", + "account_pool", + "qwen_client", + "file_store", + "session_affinity", + "upstream_file_cache", + ) + missing = [name for name in required_state if not hasattr(request.app.state, name)] + if missing: + raise HTTPException(status_code=503, detail={"status": "not_ready", "missing": missing}) + return {"status": "ready"} + + +@router.get("/admin/dev/captures", dependencies=[Depends(verify_admin)]) +async def get_captures(request: Request): + db: AsyncJsonDB = request.app.state.captures_db + return {"captures": await db.get()} + + +@router.delete("/admin/dev/captures", dependencies=[Depends(verify_admin)]) +async def clear_captures(request: Request): + db: AsyncJsonDB = request.app.state.captures_db + await db.save([]) + return {"status": "cleared"} \ No newline at end of file diff --git a/backend/api/v1_chat.py b/backend/api/v1_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..0db7699308e576fc2b05b6fcb87daf96ef36af4c --- /dev/null +++ b/backend/api/v1_chat.py @@ -0,0 +1,235 @@ +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse, StreamingResponse +import json +import logging +import time +import uuid +from typing import Any, Awaitable, Callable +from backend.adapter.standard_request import StandardRequest +from backend.core.config import settings +from backend.core.request_logging import new_request_id, request_context, update_request_context +from backend.services.attachment_preprocessor import preprocess_attachments +from backend.services.context_attachment_manager import prepare_context_attachments, derive_session_key +from backend.services.auth_quota import resolve_auth_context +from backend.services.completion_bridge import run_retryable_completion_bridge +from backend.services.openai_stream_translator import OpenAIStreamTranslator +from backend.services.prompt_builder import CLAUDE_CODE_OPENAI_PROFILE, OPENCLAW_OPENAI_PROFILE +from backend.services.response_formatters import build_openai_completion_payload +from backend.services.qwen_client import QwenClient +from backend.services.standard_request_builder import build_chat_standard_request +from backend.services.task_session import ( + build_openai_assistant_history_message, + clear_invalidated_session_chat, + log_session_plan_reuse_cancelled, + persist_session_turn, + plan_persistent_session_turn, +) +from backend.runtime.execution import RuntimeAttemptState, build_tool_directive, build_usage_delta_factory, request_max_attempts + +log = logging.getLogger("qwen2api.chat") +router = APIRouter() +OpenAIDeltaHandler = Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] + + +def _detect_openai_client_profile(request: Request, req_data: dict) -> str: + del req_data + if request.headers.get("x-anthropic-billing-header"): + return CLAUDE_CODE_OPENAI_PROFILE + return OPENCLAW_OPENAI_PROFILE + + +def _build_standard_request(req_data: dict, *, client_profile: str) -> StandardRequest: + standard_request = build_chat_standard_request( + req_data, + default_model="gpt-3.5-turbo", + surface="openai", + client_profile=client_profile, + ) + log.info("[OAI] normalized tools=%s profile=%s", standard_request.tool_names, client_profile) + return standard_request + + +@router.post("/chat/completions") +@router.post("/v1/chat/completions") +async def chat_completions(request: Request): + app = request.app + users_db = app.state.users_db + client: QwenClient = app.state.qwen_client + + auth = await resolve_auth_context(request, users_db) + token = auth.token + + try: + req_data = await request.json() + except Exception: + raise HTTPException(400, {"error": {"message": "Invalid JSON body", "type": "invalid_request_error"}}) + + client_profile = _detect_openai_client_profile(request, req_data) + session_key = derive_session_key("openai", token, req_data) + original_history_messages = req_data.get("messages", []) + file_store = getattr(app.state, "file_store", None) + preprocessed = None + if file_store is not None: + preprocessed = await preprocess_attachments(req_data, file_store, owner_token=token) + req_data = preprocessed.payload + context_prepared = await prepare_context_attachments(app=app, payload=req_data, surface="openai", auth_token=token, client_profile=client_profile, existing_attachments=(preprocessed.attachments if preprocessed is not None else None)) + req_data = context_prepared["payload"] + standard_request = _build_standard_request(req_data, client_profile=client_profile) + if preprocessed is not None: + standard_request.attachments = preprocessed.attachments + standard_request.uploaded_file_ids = preprocessed.uploaded_file_ids + standard_request.upstream_files = context_prepared["upstream_files"] + standard_request.session_key = context_prepared["session_key"] + standard_request.context_mode = context_prepared["context_mode"] + standard_request.bound_account_email = context_prepared["bound_account_email"] + standard_request.bound_account = context_prepared["bound_account"] + + session_plan = await plan_persistent_session_turn(app=app, request=standard_request, payload=req_data, surface="openai") + if session_plan.enabled: + standard_request.persistent_session = True + standard_request.full_prompt = session_plan.full_prompt + standard_request.prompt = session_plan.prompt + standard_request.session_message_hashes = session_plan.current_hashes + standard_request.upstream_chat_id = session_plan.existing_chat_id if session_plan.reuse_chat else None + if standard_request.bound_account is None and session_plan.account_email: + standard_request.bound_account = await app.state.account_pool.acquire_wait_preferred(session_plan.account_email, timeout=60) + if standard_request.bound_account is not None: + standard_request.bound_account_email = standard_request.bound_account.email + elif standard_request.bound_account is not None and not standard_request.bound_account_email: + standard_request.bound_account_email = standard_request.bound_account.email + if standard_request.upstream_chat_id and standard_request.bound_account is None: + log_session_plan_reuse_cancelled( + request=standard_request, + planned_chat_id=session_plan.existing_chat_id, + reason="missing_bound_account", + ) + standard_request.upstream_chat_id = None + standard_request.prompt = standard_request.full_prompt or standard_request.prompt + + model_name = standard_request.response_model + qwen_model = standard_request.resolved_model + prompt = standard_request.prompt + tools = standard_request.tools + history_messages = original_history_messages + + completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}" + created = int(time.time()) + + with request_context(req_id=new_request_id(), surface="openai", requested_model=model_name, resolved_model=qwen_model): + log.info( + "[OAI] model=%s stream=%s tool_enabled=%s profile=%s tools=%s prompt_len=%s prompt_tail=%r", + qwen_model, + standard_request.stream, + standard_request.tool_enabled, + standard_request.client_profile, + [t.get('name') for t in tools], + len(prompt), + prompt[-500:], + ) + + if standard_request.stream: + async def generate(): + async with app.state.session_locks.hold(session_key): + try: + update_request_context(stream_attempt=1) + translator = OpenAIStreamTranslator( + completion_id=completion_id, + created=created, + model_name=model_name, + client_profile=standard_request.client_profile, + build_final_directive=lambda answer_text: build_tool_directive( + standard_request, + RuntimeAttemptState(answer_text=answer_text), + ), + allowed_tool_names=standard_request.tool_names, + ) + + async def on_delta(evt: dict[str, Any], text_chunk: str | None, tool_calls: list[dict[str, Any]] | None) -> None: + translator.on_delta(evt, text_chunk, tool_calls) + + result = await run_retryable_completion_bridge( + client=client, + standard_request=standard_request, + prompt=prompt, + users_db=users_db, + token=token, + history_messages=history_messages, + max_attempts=request_max_attempts(standard_request), + usage_delta_factory=build_usage_delta_factory(prompt), + allow_after_visible_output=True, + capture_events=False, + on_delta=on_delta, + ) + execution = result.execution + directive = result.directive or build_tool_directive(standard_request, execution.state) + assistant_message = build_openai_assistant_history_message( + execution=execution, + request=standard_request, + directive=directive, + ) + await persist_session_turn( + app=app, + request=standard_request, + surface="openai", + execution=execution, + assistant_message=assistant_message, + ) + final_finish_reason = "tool_calls" if directive.stop_reason == "tool_use" else execution.state.finish_reason + for chunk in translator.finalize(final_finish_reason): + yield chunk + return + except HTTPException as he: + await clear_invalidated_session_chat(app=app, request=standard_request) + yield f"data: {json.dumps({'error': he.detail})}\n\n" + return + except Exception as e: + await clear_invalidated_session_chat(app=app, request=standard_request) + yield f"data: {json.dumps({'error': str(e)})}\n\n" + return + + return StreamingResponse( + generate(), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + + try: + async with app.state.session_locks.hold(session_key): + update_request_context(stream_attempt=1) + result = await run_retryable_completion_bridge( + client=client, + standard_request=standard_request, + prompt=prompt, + users_db=users_db, + token=token, + history_messages=history_messages, + max_attempts=request_max_attempts(standard_request), + usage_delta_factory=build_usage_delta_factory(prompt), + allow_after_visible_output=True, + ) + execution = result.execution + directive = result.directive or build_tool_directive(standard_request, execution.state) + assistant_message = build_openai_assistant_history_message( + execution=execution, + request=standard_request, + directive=directive, + ) + await persist_session_turn( + app=app, + request=standard_request, + surface="openai", + execution=execution, + assistant_message=assistant_message, + ) + + return JSONResponse(build_openai_completion_payload( + completion_id=completion_id, + created=created, + model_name=model_name, + prompt=result.prompt, + execution=execution, + standard_request=standard_request, + )) + except Exception as e: + await clear_invalidated_session_chat(app=app, request=standard_request) + raise HTTPException(status_code=500, detail=str(e)) diff --git a/backend/api/videos.py b/backend/api/videos.py new file mode 100644 index 0000000000000000000000000000000000000000..78e13990343731368fd9ff4dd7abf9c06b1a0e48 --- /dev/null +++ b/backend/api/videos.py @@ -0,0 +1,652 @@ +import asyncio +import json +import logging +import os +import re +import time +import uuid +from typing import Any + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse + +from backend.services.qwen_client import QwenClient + +log = logging.getLogger("qwen2api.videos") +router = APIRouter() + +DEFAULT_VIDEO_MODEL = "qwen3.6-plus" +VIDEO_BUSY_EMAILS: set[str] = set() +VIDEO_BUSY_LOCK = asyncio.Lock() + +# Async task store for NewAPI/ArcReel polling protocol. +# ArcReel's newapi-video backend expects: +# POST /v1/video/generations -> {"task_id": "..."} +# GET /v1/video/generations/{task_id} -> {"status":"completed","url":"..."} +# The old sync path waited ~90s and exceeded ArcReel's 60s create timeout +# (create_ambiguous). Background jobs fix that. +VIDEO_TASKS: dict[str, dict[str, Any]] = {} +VIDEO_TASKS_LOCK = asyncio.Lock() +VIDEO_TASK_TTL_SECONDS = 3600 + +VIDEO_MODEL_MAP = { + "sora": "qwen3.6-plus", + "sora-1.0-turbo": "qwen3.6-plus", + "qwen-video": "qwen3.6-plus", + "qwen-video-plus": "qwen3.6-plus", + "qwen3.6-plus": "qwen3.6-plus", +} + +HTTP_URL_RE = re.compile(r"https?://[^\s\"'<>)]*", re.IGNORECASE) +VIDEO_EXT_RE = re.compile(r"\.(?:mp4|webm|mov|m3u8|m4v)(?:[?#]|$)", re.IGNORECASE) +IMAGE_EXT_RE = re.compile(r"\.(?:jpg|jpeg|png|webp|gif|svg)(?:[?#]|$)", re.IGNORECASE) + + +def _resolve_video_model(requested: str | None) -> str: + if not requested: + return DEFAULT_VIDEO_MODEL + return VIDEO_MODEL_MAP.get(requested, DEFAULT_VIDEO_MODEL) + + +def _get_token(request: Request) -> str: + auth = request.headers.get("Authorization", "") + if auth.startswith("Bearer "): + return auth[7:].strip() + return request.headers.get("x-api-key", "").strip() + + +def _looks_like_video_url(url: str, key_hint: str = "") -> bool: + lowered = url.lower().rstrip(".,;)\"'>") + if IMAGE_EXT_RE.search(lowered): + return False + if VIDEO_EXT_RE.search(lowered): + return True + hint = key_hint.lower() + if any(token in hint for token in ("video", "media", "download", "play")): + return True + return any(token in lowered for token in ("/video", "video_", "video-", "/videos", "m3u8")) + + +def _extract_video_urls(value: Any, key_hint: str = "") -> list[str]: + urls: list[str] = [] + + if value is None: + return urls + + if isinstance(value, str): + for raw_url in HTTP_URL_RE.findall(value): + url = raw_url.rstrip(".,;)\"'>") + if _looks_like_video_url(url, key_hint): + urls.append(url) + return urls + + if isinstance(value, list): + for item in value: + urls.extend(_extract_video_urls(item, key_hint)) + return urls + + if isinstance(value, dict): + for key, item in value.items(): + next_hint = str(key) + urls.extend(_extract_video_urls(item, next_hint)) + return urls + + return urls + + +def _extract_task_ids(value: Any) -> list[str]: + task_ids: list[str] = [] + + if value is None: + return task_ids + + if isinstance(value, list): + for item in value: + task_ids.extend(_extract_task_ids(item)) + return task_ids + + if isinstance(value, dict): + for key, item in value.items(): + if key in {"task_id", "taskId"} and isinstance(item, str) and item.strip(): + task_ids.append(item.strip()) + else: + task_ids.extend(_extract_task_ids(item)) + + return task_ids + + +def _dedupe(values: list[str]) -> list[str]: + seen: set[str] = set() + result: list[str] = [] + for value in values: + if value not in seen: + seen.add(value) + result.append(value) + return result + + +def _build_video_prompt(prompt: str, size: str | None) -> str: + return prompt + + +def _decode_image_input(image_value: str) -> tuple[bytes, str, str]: + """Return (raw_bytes, content_type, filename) from data-url or http(s) url.""" + import base64 + import mimetypes + import urllib.request + + value = (image_value or "").strip() + if not value: + raise HTTPException(status_code=400, detail="empty image") + + if value.startswith("data:"): + header, b64 = value.split(",", 1) + content_type = "image/png" + if ";" in header: + content_type = header[5:].split(";")[0] or content_type + raw = base64.b64decode(b64) + ext = mimetypes.guess_extension(content_type) or ".png" + return raw, content_type, f"ref{ext}" + + if value.startswith("http://") or value.startswith("https://"): + req = urllib.request.Request(value, headers={"User-Agent": "qwen2api-video/1.0"}) + with urllib.request.urlopen(req, timeout=60) as resp: + raw = resp.read() + content_type = resp.headers.get("Content-Type") or "image/png" + ext = mimetypes.guess_extension(content_type.split(";")[0].strip()) or ".png" + return raw, content_type.split(";")[0].strip(), f"ref{ext}" + + # local path + if os.path.exists(value): + raw = open(value, "rb").read() + content_type = mimetypes.guess_type(value)[0] or "image/png" + return raw, content_type, os.path.basename(value) or "ref.png" + + raise HTTPException(status_code=400, detail="image must be data-url, http(s) url, or local path") + + +async def _upload_reference_images(client: QwenClient, acc: Any, images: list[str]) -> list[dict]: + """Upload one or more reference images and return remote file refs for complete_once(files=...).""" + if not images: + return [] + + from backend.core.config import settings + from backend.services.upstream_file_uploader import UpstreamFileUploader + + uploader = UpstreamFileUploader(client, settings) + files: list[dict] = [] + tmp_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "logs", "video_refs") + os.makedirs(tmp_dir, exist_ok=True) + + for idx, image_value in enumerate(images[:4]): + raw, content_type, filename = _decode_image_input(image_value) + local_path = os.path.join(tmp_dir, f"{int(time.time())}_{idx}_{filename}") + with open(local_path, "wb") as f: + f.write(raw) + meta = { + "filename": filename, + "path": local_path, + "content_type": content_type, + "size": len(raw), + } + remote = await uploader.upload_local_file(acc, meta) + ref = remote.get("remote_ref") + put_url = "" + if isinstance(ref, dict): + put_url = str(ref.get("url") or "") + if not put_url: + # fallback construct from uploader fields if present + put_url = str(remote.get("url") or "") + + # Frontend real i2v file object (from chat.qwen.ai frontend_main.js): + # {type:"image", name, file_type, showType:"image", status:"uploaded", + # file_class:"vision", url} + # When VideoGeneration + image file is present, frontend auto-switches to i2v. + vision_ref = { + "type": "image", + "name": filename, + "file_type": content_type if content_type.startswith("image/") else "image/png", + "showType": "image", + "status": "uploaded", + "file_class": "vision", + "url": put_url, + } + # Keep upstream file id if available (some servers use it). + if isinstance(ref, dict): + if ref.get("id"): + vision_ref["id"] = ref.get("id") + if isinstance(ref.get("file"), dict) and ref["file"].get("id"): + vision_ref["file"] = ref["file"] + # merge non-conflicting extras + for k in ("itemId", "uploadTaskId", "size", "greenNet", "progress", "error", "collection_name"): + if k in ref and k not in vision_ref: + vision_ref[k] = ref[k] + + if not vision_ref.get("url"): + log.warning("[T2V] upload missing url, remote=%s", remote) + files.append(vision_ref) + log.info( + "[T2V] uploaded reference image file_id=%s name=%s url=%s type=%s class=%s", + remote.get("remote_file_id"), + filename, + (vision_ref.get("url") or "")[:120], + vision_ref.get("type"), + vision_ref.get("file_class"), + ) + return files + + +def _collect_images_from_body(body: dict) -> list[str]: + images: list[str] = [] + for key in ("image", "image_url", "reference_image", "ref_image"): + val = body.get(key) + if isinstance(val, str) and val.strip(): + images.append(val.strip()) + for key in ("images", "image_urls", "reference_images"): + val = body.get(key) + if isinstance(val, list): + for item in val: + if isinstance(item, str) and item.strip(): + images.append(item.strip()) + elif isinstance(item, dict): + u = item.get("url") or item.get("image_url") or item.get("data") + if isinstance(u, str) and u.strip(): + images.append(u.strip()) + # de-dupe keep order + seen: set[str] = set() + out: list[str] = [] + for u in images: + if u not in seen: + seen.add(u) + out.append(u) + return out + + +def _video_account_wait_seconds() -> int: + try: + return max(30, int(os.getenv("QWEN_VIDEO_ACCOUNT_WAIT_SECONDS", "900"))) + except Exception: + return 900 + + +async def _acquire_video_account(client: QwenClient): + if client.account_pool is None: + raise HTTPException(status_code=500, detail="No upstream account pool configured") + + deadline = time.monotonic() + _video_account_wait_seconds() + + while time.monotonic() < deadline: + async with VIDEO_BUSY_LOCK: + exclude = set(VIDEO_BUSY_EMAILS) + + remaining = max(1, deadline - time.monotonic()) + acc = await client.account_pool.acquire_wait(timeout=min(10, remaining), exclude=exclude) + if acc is None: + await asyncio.sleep(2) + continue + + email = getattr(acc, "email", "") or "" + async with VIDEO_BUSY_LOCK: + if email not in VIDEO_BUSY_EMAILS: + VIDEO_BUSY_EMAILS.add(email) + return acc + + client.account_pool.release(acc) + await asyncio.sleep(1) + + raise HTTPException(status_code=503, detail="No available upstream video accounts") + + +async def _release_video_account(client: QwenClient, acc: Any): + email = getattr(acc, "email", "") or "" + async with VIDEO_BUSY_LOCK: + VIDEO_BUSY_EMAILS.discard(email) + client.account_pool.release(acc) + + +async def _poll_video_task(client: QwenClient, token: str, task_id: str, *, timeout_seconds: int = 420) -> dict: + started_at = time.monotonic() + last_status: dict = {} + + while time.monotonic() - started_at < timeout_seconds: + task_status = await client.get_task_status(token, task_id) + last_status = task_status + data = task_status.get("data") if isinstance(task_status, dict) else None + if not isinstance(data, dict) and isinstance(task_status, dict): + data = task_status + if not isinstance(data, dict): + await asyncio.sleep(5) + continue + + state = str(data.get("task_status") or data.get("status") or "").lower() + log.info("[T2V] task_id=%s status=%s", task_id, state) + if state == "success": + return task_status + if state not in {"running", "pending", "queued", "created", "processing", ""}: + raise HTTPException(status_code=500, detail={"message": "Video task failed", "task_status": data}) + + await asyncio.sleep(10) + + raise HTTPException(status_code=504, detail={"message": "Video task timed out", "task_id": task_id, "last_status": last_status}) + + +def _normalize_size(body: dict) -> str | None: + """Accept size=1280*720 or ArcReel/newapi width+height.""" + size = str(body.get("size", "")).strip() or None + if size: + return size + width = body.get("width") + height = body.get("height") + try: + if width and height: + return f"{int(width)}*{int(height)}" + except Exception: + pass + return None + + +async def _purge_old_video_tasks() -> None: + now = time.time() + async with VIDEO_TASKS_LOCK: + dead = [tid for tid, t in VIDEO_TASKS.items() if now - float(t.get("created_at", now)) > VIDEO_TASK_TTL_SECONDS] + for tid in dead: + VIDEO_TASKS.pop(tid, None) + + +async def _set_video_task(task_id: str, **fields: Any) -> None: + async with VIDEO_TASKS_LOCK: + cur = VIDEO_TASKS.get(task_id) or {"task_id": task_id, "created_at": time.time()} + cur.update(fields) + cur["updated_at"] = time.time() + VIDEO_TASKS[task_id] = cur + + +async def _get_video_task(task_id: str) -> dict[str, Any] | None: + async with VIDEO_TASKS_LOCK: + return dict(VIDEO_TASKS.get(task_id) or {}) or None + + +async def _run_video_job(app: Any, task_id: str, body: dict) -> None: + """Background worker: full Qwen t2v/i2v pipeline, then update VIDEO_TASKS.""" + from backend.core.config import settings # noqa: F401 + + client: QwenClient = app.state.qwen_client + prompt = str(body.get("prompt", "")).strip() + n = min(max(int(body.get("n", 1)), 1), 4) + model = _resolve_video_model(body.get("model")) + size = _normalize_size(body) + ref_images = _collect_images_from_body(body) + duration = body.get("duration") or body.get("duration_seconds") + + await _set_video_task(task_id, status="processing", model=model, prompt=prompt[:200]) + log.info("[T2V-ASYNC] start task_id=%s model=%s refs=%s size=%s", task_id, model, len(ref_images), size) + + acc = None + chat_id = None + try: + prompt_text = _build_video_prompt(prompt, size) + if ref_images: + prompt_text = ( + "Use the attached reference image(s) as strict character/appearance identity lock. " + "Keep face, hair, clothes and body proportions consistent with the reference. " + "Do not invent a different character.\n\n" + prompt_text + ) + + max_account_tries = 7 + tried_emails: set[str] = set() + last_completion: Any = None + last_chat_detail: Any = None + video_urls: list[str] = [] + + for attempt in range(1, max_account_tries + 1): + if acc is None: + acc = await _acquire_video_account(client) + email = getattr(acc, "email", "") or "" + if email: + tried_emails.add(email) + + files = [] + img_url = None + if ref_images: + try: + files = await _upload_reference_images(client, acc, ref_images) + for f in files: + if isinstance(f, dict) and isinstance(f.get("url"), str) and f["url"].startswith("http"): + img_url = f["url"] + break + except Exception as upload_error: + log.warning("[T2V-ASYNC] reference upload failed on %s: %s", email, upload_error) + files = [] + img_url = None + + message_type = "i2v" if (files and img_url) else "t2v" + try: + chat_id = await client.create_chat(acc.token, model, chat_type="t2v") + chat_type = message_type + except Exception as chat_error: + log.warning("[T2V-ASYNC] create_chat failed on %s: %s", email, chat_error) + await _release_video_account(client, acc) + acc = None + chat_id = None + continue + + log.info( + "[T2V-ASYNC] task=%s try=%s chat_id=%s account=%s chat_type=%s files=%s", + task_id, + attempt, + chat_id, + email, + chat_type, + len(files), + ) + + completion = await client.complete_once( + acc.token, + chat_id, + model, + prompt_text, + has_custom_tools=False, + files=files or None, + chat_type=chat_type, + size=size, + img_url=img_url, + ) + last_completion = completion + + if isinstance(completion, dict): + data_obj = completion.get("data") if isinstance(completion.get("data"), dict) else {} + code = str((data_obj or {}).get("code") or completion.get("code") or "") + details = str((data_obj or {}).get("details") or completion.get("details") or "") + success_flag = completion.get("success") + if success_flag is False or code in {"RateLimited", "rate_limited", "QuotaExceeded"} or "limit" in details.lower(): + log.warning("[T2V-ASYNC] limited email=%s code=%s details=%s", email, code, details) + if chat_id: + asyncio.create_task(client.delete_chat(acc.token, chat_id)) + chat_id = None + await _release_video_account(client, acc) + acc = None + if attempt >= max_account_tries: + await _set_video_task( + task_id, + status="failed", + error={"message": details or "RateLimited on all accounts", "code": code or "RateLimited"}, + tried_accounts=list(tried_emails), + ) + return + continue + + chat_detail = None + try: + chat_detail = await client.get_chat(acc.token, chat_id) + last_chat_detail = chat_detail + except Exception as chat_error: + log.warning("[T2V-ASYNC] failed to fetch chat detail: %s", chat_error) + + search_payload: list[Any] = [completion] + if chat_detail: + search_payload.append(chat_detail) + + task_ids = _dedupe(_extract_task_ids(search_payload)) + if task_ids: + log.info("[T2V-ASYNC] extracted upstream task IDs: %s", task_ids) + try: + task_result = await _poll_video_task(client, acc.token, task_ids[0]) + search_payload.append(task_result) + except HTTPException as poll_err: + log.warning("[T2V-ASYNC] poll failed on %s: %s", email, poll_err.detail) + if chat_id: + asyncio.create_task(client.delete_chat(acc.token, chat_id)) + chat_id = None + await _release_video_account(client, acc) + acc = None + continue + + video_urls = _dedupe(_extract_video_urls(search_payload)) + log.info("[T2V-ASYNC] extracted %s video URLs", len(video_urls)) + if video_urls: + break + + if chat_id: + asyncio.create_task(client.delete_chat(acc.token, chat_id)) + chat_id = None + await _release_video_account(client, acc) + acc = None + + if not video_urls: + debug_path = os.path.join( + os.path.dirname(os.path.dirname(os.path.dirname(__file__))), + "logs", + f"t2v-async-{task_id}.json", + ) + try: + with open(debug_path, "w", encoding="utf-8") as f: + json.dump( + {"completion": last_completion, "chat": last_chat_detail, "tried": list(tried_emails)}, + f, + ensure_ascii=False, + indent=2, + ) + except Exception: + pass + await _set_video_task( + task_id, + status="failed", + error={"message": "Video generation produced no URL"}, + tried_accounts=list(tried_emails), + ) + return + + url = video_urls[0] + meta: dict[str, Any] = {} + if duration is not None: + try: + meta["duration"] = int(float(duration)) + except Exception: + pass + await _set_video_task( + task_id, + status="completed", + url=url, + urls=video_urls[:n], + metadata=meta, + data=[{"url": u, "revised_prompt": prompt} for u in video_urls[:n]], + ) + log.info("[T2V-ASYNC] completed task_id=%s url=%s", task_id, url[:120]) + except Exception as e: + log.exception("[T2V-ASYNC] task_id=%s failed: %s", task_id, e) + await _set_video_task(task_id, status="failed", error={"message": str(e)}) + finally: + if acc is not None: + await _release_video_account(client, acc) + if chat_id: + asyncio.create_task(client.delete_chat(acc.token, chat_id)) + + +@router.get("/v1/videos/generations/{task_id}") +@router.get("/v1/video/generations/{task_id}") +@router.get("/videos/generations/{task_id}") +@router.get("/video/generations/{task_id}") +async def get_video_task(task_id: str, request: Request): + """NewAPI/ArcReel poll endpoint.""" + from backend.core.config import API_KEYS, settings + + token = _get_token(request) + if API_KEYS: + if token != settings.ADMIN_KEY and token not in API_KEYS: + raise HTTPException(status_code=401, detail="Invalid API Key") + + task = await _get_video_task(task_id) + if not task: + raise HTTPException(status_code=404, detail=f"task not found: {task_id}") + + status = task.get("status") or "queued" + body: dict[str, Any] = { + "task_id": task_id, + "status": status, + "model": task.get("model"), + } + if status == "completed": + body["url"] = task.get("url") + body["metadata"] = task.get("metadata") or {} + if task.get("data"): + body["data"] = task["data"] + elif status == "failed": + body["error"] = task.get("error") or {"message": "unknown"} + return JSONResponse(body) + + +@router.post("/v1/videos/generations") +@router.post("/v1/video/generations") +@router.post("/videos/generations") +@router.post("/video/generations") +async def create_video(request: Request): + """Create video. + + Default = **async NewAPI protocol** (immediate task_id) for ArcReel. + Pass ``{"wait": true}`` to block until finished and return the old + ``{"data":[{"url":...}]}`` shape (for scripts / manual tests). + """ + from backend.core.config import API_KEYS, settings + + token = _get_token(request) + if API_KEYS: + if token != settings.ADMIN_KEY and token not in API_KEYS: + raise HTTPException(status_code=401, detail="Invalid API Key") + + try: + body = await request.json() + except Exception: + raise HTTPException(status_code=400, detail="Invalid JSON body") + + prompt = str(body.get("prompt", "")).strip() + if not prompt: + raise HTTPException(status_code=400, detail="prompt is required") + + await _purge_old_video_tasks() + wait = bool(body.get("wait") is True or str(body.get("wait", "")).lower() in {"1", "true", "yes"}) + + task_id = f"qv_{uuid.uuid4().hex[:16]}" + await _set_video_task(task_id, status="queued", model=_resolve_video_model(body.get("model")), prompt=prompt[:200]) + asyncio.create_task(_run_video_job(request.app, task_id, body)) + log.info("[T2V] queued task_id=%s wait=%s prompt=%r", task_id, wait, prompt[:80]) + + if not wait: + # ArcReel / NewAPI path — return immediately so create never times out. + return JSONResponse({"task_id": task_id, "status": "queued", "created": int(time.time())}) + + # Sync wait path for scripts. + deadline = time.monotonic() + int(body.get("timeout", 600) or 600) + while time.monotonic() < deadline: + task = await _get_video_task(task_id) + if not task: + break + st = task.get("status") + if st == "completed": + data = task.get("data") or [{"url": task.get("url"), "revised_prompt": prompt}] + return JSONResponse({"created": int(time.time()), "data": data, "task_id": task_id}) + if st == "failed": + err = task.get("error") or {} + raise HTTPException(status_code=500, detail=err.get("message") or "video failed") + await asyncio.sleep(2) + + raise HTTPException(status_code=504, detail={"message": "wait timeout", "task_id": task_id}) diff --git a/backend/core/__init__.py b/backend/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8bac0e66de4b043285ce4d887680f8df5c67d104 --- /dev/null +++ b/backend/core/__init__.py @@ -0,0 +1 @@ +# Backend core package diff --git a/backend/core/account_pool/__init__.py b/backend/core/account_pool/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da4d6c7e292306bb9a3cf9bad11bae2c0ecd619b --- /dev/null +++ b/backend/core/account_pool/__init__.py @@ -0,0 +1,23 @@ +""" +账号池 - 完整实现(对齐 ds2api) + +将 pool_core.py 和 pool_acquire.py 合并为完整的 AccountPool +""" +from backend.core.account_pool.pool_core import Account, AccountPool as CorePool +from backend.core.account_pool.pool_acquire import AccountAcquireMixin + + +class AccountPool(AccountAcquireMixin, CorePool): + """ + 完整的账号池实现 + + 对齐 ds2api 的 4 层并发控制: + 1. max_inflight_per_account: 每账号最大并发 + 2. recommended_concurrency: 推荐并发值 + 3. max_queue_size: 等待队列上限 + 4. global_max_inflight: 全局最大并发 + """ + pass + + +__all__ = ["Account", "AccountPool"] diff --git a/backend/core/account_pool/pool_acquire.py b/backend/core/account_pool/pool_acquire.py new file mode 100644 index 0000000000000000000000000000000000000000..46096ceb4f1e1ea68e8b0c5af812d8a5cb755f09 --- /dev/null +++ b/backend/core/account_pool/pool_acquire.py @@ -0,0 +1,252 @@ +""" +账号获取逻辑 - 对齐 ds2api 的 pool_acquire.go +""" +import asyncio +import logging +import random +import time +from typing import Optional, TYPE_CHECKING + +from backend.core.config import settings + +if TYPE_CHECKING: + from backend.core.account_pool.pool_core import Account + +log = logging.getLogger("qwen2api.accounts.acquire") + + +def _jitter_seconds() -> float: + """随机抖动""" + low = max(0, settings.REQUEST_JITTER_MIN_MS) + high = max(low, settings.REQUEST_JITTER_MAX_MS) + return random.uniform(low, high) / 1000.0 + + +class AccountAcquireMixin: + """账号获取逻辑混入类""" + + async def _remove_waiter(self, waiter: asyncio.Event) -> None: + """ + 从等待队列中移除 waiter(若仍在队列中)。 + + acquire_wait* 可能因超时返回;若不清理 waiter,队列长度会持续增长, + 在 max_queue_size 较小时会出现“队列假满”并拒绝后续请求。 + """ + async with self._lock: + queue = getattr(self._waiters_queue, "_queue", None) + if queue is None: + return + try: + queue.remove(waiter) + except ValueError: + # 已被 release() 的 notify 弹出,属于正常竞争场景 + pass + + async def acquire(self, exclude: Optional[set] = None) -> Optional["Account"]: + """ + 立即获取账号(不等待) + 对齐 ds2api 的 Acquire() 逻辑 + """ + async with self._lock: + now = time.time() + + # 检查全局并发限制 + if not self._can_acquire_global(): + return None + + # 筛选可用账号 + available = [a for a in self.accounts if a.is_available() and (not exclude or a.email not in exclude)] + if not available: + return None + + # 筛选就绪账号(未达到并发上限且冷却完成) + ready = [a for a in available if a.inflight < self.max_inflight_per_account and a.next_available_at() <= now] + if not ready: + return None + + # 按负载排序:优先选择 inflight 最少的账号 + ready.sort(key=lambda a: (a.inflight, a.last_request_started or 0.0, a.last_used or 0.0)) + best = ready[0] + + # 分配账号 + best.inflight += 1 + best.last_used = now + best.last_request_started = now + _jitter_seconds() + self.global_in_use += 1 + self._sticky_email = best.email if len(ready) == 1 else None + + return best + + async def acquire_preferred(self, preferred_email: Optional[str] = None, exclude: Optional[set] = None) -> Optional["Account"]: + """ + 优先获取指定账号 + 对齐 ds2api 的 AcquirePreferred() 逻辑 + """ + if not preferred_email: + return await self.acquire(exclude) + + async with self._lock: + now = time.time() + + # 检查全局并发限制 + if not self._can_acquire_global(): + return None + + # 查找指定账号 + preferred = next((a for a in self.accounts if a.email == preferred_email), None) + if ( + preferred + and preferred.is_available() + and preferred.inflight < self.max_inflight_per_account + and preferred.next_available_at() <= now + and (not exclude or preferred.email not in exclude) + ): + preferred.inflight += 1 + preferred.last_used = now + preferred.last_request_started = now + _jitter_seconds() + self.global_in_use += 1 + self._sticky_email = preferred.email + return preferred + + # 指定账号不可用,回退到普通获取 + return await self.acquire(exclude) + + async def acquire_wait(self, timeout: float = 60, exclude: Optional[set] = None) -> Optional["Account"]: + """ + 等待获取账号(带超时) + 对齐 ds2api 的 AcquireWait() 逻辑 + """ + deadline = time.time() + timeout + + while True: + # 尝试立即获取 + acc = await self.acquire(exclude) + if acc: + return acc + + # 检查是否还有候选账号 + async with self._lock: + candidates = [a for a in self.accounts if a.valid and (not exclude or a.email not in exclude)] + if not candidates: + return None + + # 计算下次可用时间 + next_ready_at = min((a.next_available_at() for a in candidates), default=time.time()) + + # 检查超时 + remaining = deadline - time.time() + if remaining <= 0: + return None + + # 检查队列是否已满 + if not self._can_queue(): + log.warning(f"[AccountPool] 等待队列已满 ({self._waiters_queue.qsize()}/{self.max_queue_size})") + return None + + # 加入等待队列 + waiter = asyncio.Event() + await self._waiters_queue.put(waiter) + + # 计算等待时间 + wait_timeout = min(remaining, max(0.05, next_ready_at - time.time() + 0.05)) + + try: + await asyncio.wait_for(waiter.wait(), timeout=wait_timeout) + except asyncio.TimeoutError: + pass + finally: + await self._remove_waiter(waiter) + + async def acquire_wait_preferred( + self, preferred_email: Optional[str] = None, timeout: float = 60, exclude: Optional[set] = None + ) -> Optional["Account"]: + """ + 等待获取指定账号 + 对齐 ds2api 的 AcquireWaitPreferred() 逻辑 + """ + deadline = time.time() + timeout + + while True: + acc = await self.acquire_preferred(preferred_email, exclude) + if acc: + return acc + + remaining = deadline - time.time() + if remaining <= 0: + return None + + if not self._can_queue(): + return None + + waiter = asyncio.Event() + await self._waiters_queue.put(waiter) + + try: + await asyncio.wait_for(waiter.wait(), timeout=min(remaining, 0.5)) + except asyncio.TimeoutError: + pass + finally: + await self._remove_waiter(waiter) + + def release(self, acc: "Account"): + """ + 释放账号 + 对齐 ds2api 的 Release() 逻辑 + """ + if not acc or not acc.email: + return + + acc.inflight = max(0, acc.inflight - 1) + acc.last_request_finished = time.time() + self.global_in_use = max(0, self.global_in_use - 1) + + # 唤醒等待队列中的第一个 + self._notify_waiter() + + def _notify_waiter(self): + """ + 唤醒等待队列中的第一个等待者 + 对齐 ds2api 的 notifyWaiterLocked() + """ + if self._waiters_queue.empty(): + return + + try: + waiter = self._waiters_queue.get_nowait() + waiter.set() # 唤醒 + except asyncio.QueueEmpty: + pass + + def mark_invalid(self, acc: "Account", reason: str = "invalid", error_message: str = ""): + """标记账号为不可用""" + acc.valid = False + acc.status_code = reason or "invalid" + acc.last_error = error_message or acc.last_error + acc.consecutive_failures += 1 + if reason == "pending_activation": + acc.activation_pending = True + if self._sticky_email == acc.email: + self._sticky_email = None + log.warning(f"[账号] {acc.email} 已标记为不可用,状态={acc.status_code}") + + def mark_success(self, acc: "Account"): + """标记账号请求成功""" + acc.consecutive_failures = 0 + acc.rate_limit_strikes = 0 + if acc.status_code == "rate_limited": + acc.status_code = "valid" + if not acc.activation_pending: + acc.valid = True + + def mark_rate_limited(self, acc: "Account", cooldown: int | None = None, error_message: str = ""): + """标记账号被限流""" + acc.rate_limit_strikes += 1 + base = cooldown if cooldown is not None else settings.RATE_LIMIT_BASE_COOLDOWN + dynamic = min(settings.RATE_LIMIT_MAX_COOLDOWN, int(base * (2 ** max(0, acc.rate_limit_strikes - 1)))) + dynamic += int(_jitter_seconds()) + acc.rate_limited_until = time.time() + dynamic + acc.status_code = "rate_limited" + acc.last_error = error_message or acc.last_error + if self._sticky_email == acc.email: + self._sticky_email = None + log.warning(f"[账号] {acc.email} 已限流冷却 {dynamic} 秒") diff --git a/backend/core/account_pool/pool_core.py b/backend/core/account_pool/pool_core.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd9385df2d0426c0cf40ceb3e3ab9eb2ca92d0c --- /dev/null +++ b/backend/core/account_pool/pool_core.py @@ -0,0 +1,216 @@ +""" +账号池核心逻辑 - 对齐 ds2api 的 pool_core.go +""" +import asyncio +import logging +import time +from typing import Optional + +from backend.core.database import AsyncJsonDB +from backend.core.config import settings + +log = logging.getLogger("qwen2api.accounts.core") + + +class Account: + """账号对象""" + def __init__( + self, + email="", + password="", + token="", + cookies="", + username="", + activation_pending=False, + status_code="", + last_error="", + **kwargs, + ): + self.email = email + self.password = password + self.token = token + self.cookies = cookies + self.username = username + self.activation_pending = activation_pending + self.valid = not activation_pending + self.last_used = 0.0 + self.inflight = 0 + self.rate_limited_until = 0.0 + self.healing = False + self.status_code = status_code or ("pending_activation" if activation_pending else "valid") + self.last_error = last_error or "" + self.last_request_started = float(kwargs.get("last_request_started", 0.0) or 0.0) + self.last_request_finished = float(kwargs.get("last_request_finished", 0.0) or 0.0) + self.consecutive_failures = int(kwargs.get("consecutive_failures", 0) or 0) + self.rate_limit_strikes = int(kwargs.get("rate_limit_strikes", 0) or 0) + + def is_rate_limited(self) -> bool: + return self.rate_limited_until > time.time() + + def is_available(self) -> bool: + return self.valid and not self.is_rate_limited() + + def next_available_at(self) -> float: + min_interval = max(0, settings.ACCOUNT_MIN_INTERVAL_MS) / 1000.0 + return max(self.rate_limited_until, self.last_request_started + min_interval) + + def get_status_code(self) -> str: + if self.activation_pending: + return "pending_activation" + if self.is_rate_limited(): + return "rate_limited" + if self.valid: + return "valid" + if self.status_code == "banned": + return "banned" + if self.status_code == "auth_error": + return "auth_error" + return self.status_code or "invalid" + + def get_status_text(self) -> str: + status_map = { + "valid": "正常", + "pending_activation": "待激活", + "rate_limited": "限流", + "banned": "封禁", + "auth_error": "鉴权失败", + "invalid": "失效", + "unknown": "未知", + } + return status_map.get(self.get_status_code(), "未知") + + def to_dict(self): + return { + "email": self.email, + "password": self.password, + "token": self.token, + "cookies": self.cookies, + "username": self.username, + "activation_pending": self.activation_pending, + "status_code": self.status_code, + "last_error": self.last_error, + "last_request_started": self.last_request_started, + "last_request_finished": self.last_request_finished, + "consecutive_failures": self.consecutive_failures, + "rate_limit_strikes": self.rate_limit_strikes, + } + + +class AccountPool: + """ + 账号池 - 对齐 ds2api 的 4 层并发控制 + + 4 层限流: + 1. maxInflightPerAccount: 每账号最大并发 + 2. recommendedConcurrency: 推荐并发值(账号数 × 每账号并发) + 3. maxQueueSize: 等待队列上限 + 4. globalMaxInflight: 全局最大并发 + """ + + def __init__(self, db: AsyncJsonDB, max_inflight: int = settings.MAX_INFLIGHT_PER_ACCOUNT): + self.db = db + self.accounts: list[Account] = [] + self._lock = asyncio.Lock() + + # 4 层并发控制(对齐 ds2api) + self.max_inflight_per_account = max_inflight + self.recommended_concurrency = 0 + self.max_queue_size = 0 + self.global_max_inflight = 0 + + # 等待队列(使用 asyncio.Queue 更接近 Go channel) + self._waiters_queue: asyncio.Queue = asyncio.Queue() + self._sticky_email: Optional[str] = None + + # 全局并发计数 + self.global_in_use = 0 + + async def load(self): + """加载账号并初始化并发参数""" + data = await self.db.load() + self.accounts = [Account(**d) for d in data] if isinstance(data, list) else [] + self._reset_concurrency_limits() + log.info(f"Loaded {len(self.accounts)} upstream account(s)") + + def _reset_concurrency_limits(self): + """重置并发限制 - 对齐 ds2api 的 Reset() 逻辑""" + account_count = len([a for a in self.accounts if a.is_available()]) + + # 计算推荐并发值(对齐 ds2api) + self.recommended_concurrency = account_count * self.max_inflight_per_account + + # 队列上限 = 推荐并发值(可配置) + self.max_queue_size = self.recommended_concurrency + + # 全局并发上限 = 推荐并发值(可配置) + self.global_max_inflight = self.recommended_concurrency + + log.info( + f"[init_account_queue] initialized: " + f"total={account_count}, " + f"max_inflight_per_account={self.max_inflight_per_account}, " + f"global_max_inflight={self.global_max_inflight}, " + f"recommended_concurrency={self.recommended_concurrency}, " + f"max_queue_size={self.max_queue_size}" + ) + + async def save(self): + await self.db.save([a.to_dict() for a in self.accounts]) + + async def add(self, account: Account): + async with self._lock: + self.accounts = [a for a in self.accounts if a.email != account.email] + self.accounts.append(account) + await self.save() + self._reset_concurrency_limits() + + async def remove(self, email: str): + async with self._lock: + self.accounts = [a for a in self.accounts if a.email != email] + await self.save() + self._reset_concurrency_limits() + + def set_max_inflight(self, value: int): + self.max_inflight_per_account = max(1, int(value)) + self._reset_concurrency_limits() + + def get_by_email(self, email: str) -> Optional[Account]: + return next((a for a in self.accounts if a.email == email), None) + + def _can_acquire_global(self) -> bool: + """检查全局并发限制""" + if self.global_max_inflight <= 0: + return True + return self.global_in_use < self.global_max_inflight + + def _can_queue(self) -> bool: + """检查是否可以加入等待队列""" + if self.max_queue_size <= 0: + return False + return self._waiters_queue.qsize() < self.max_queue_size + + def status(self): + """返回账号池状态""" + available = [a for a in self.accounts if a.is_available()] + rate_limited = [a for a in self.accounts if a.get_status_code() == "rate_limited"] + invalid = [a for a in self.accounts if a.get_status_code() not in ("valid", "rate_limited")] + activation_pending = [a for a in self.accounts if a.get_status_code() == "pending_activation"] + banned = [a for a in self.accounts if a.get_status_code() == "banned"] + in_use = sum(a.inflight for a in self.accounts) + + return { + "total": len(self.accounts), + "valid": len(available), + "rate_limited": len(rate_limited), + "invalid": len(invalid), + "activation_pending": len(activation_pending), + "banned": len(banned), + "in_use": in_use, + "global_in_use": self.global_in_use, + "max_inflight_per_account": self.max_inflight_per_account, + "recommended_concurrency": self.recommended_concurrency, + "max_queue_size": self.max_queue_size, + "global_max_inflight": self.global_max_inflight, + "waiting": self._waiters_queue.qsize(), + "account_min_interval_ms": getattr(settings, "ACCOUNT_MIN_INTERVAL_MS", 0), + } diff --git a/backend/core/account_pool_old.py b/backend/core/account_pool_old.py new file mode 100644 index 0000000000000000000000000000000000000000..8be1a955faffe0e1ff04f78bf01e6ef13454cc04 --- /dev/null +++ b/backend/core/account_pool_old.py @@ -0,0 +1,275 @@ +import asyncio +import logging +import random +import time +from typing import Optional +from backend.core.database import AsyncJsonDB +from backend.core.config import settings + +log = logging.getLogger("qwen2api.accounts") + + +def _jitter_seconds() -> float: + low = max(0, settings.REQUEST_JITTER_MIN_MS) + high = max(low, settings.REQUEST_JITTER_MAX_MS) + return random.uniform(low, high) / 1000.0 + + +class Account: + def __init__( + self, + email="", + password="", + token="", + cookies="", + username="", + activation_pending=False, + status_code="", + last_error="", + **kwargs, + ): + self.email = email + self.password = password + self.token = token + self.cookies = cookies + self.username = username + self.activation_pending = activation_pending + self.valid = not activation_pending + self.last_used = 0.0 + self.inflight = 0 + self.rate_limited_until = 0.0 + self.healing = False + self.status_code = status_code or ("pending_activation" if activation_pending else "valid") + self.last_error = last_error or "" + self.last_request_started = float(kwargs.get("last_request_started", 0.0) or 0.0) + self.last_request_finished = float(kwargs.get("last_request_finished", 0.0) or 0.0) + self.consecutive_failures = int(kwargs.get("consecutive_failures", 0) or 0) + self.rate_limit_strikes = int(kwargs.get("rate_limit_strikes", 0) or 0) + + def is_rate_limited(self) -> bool: + return self.rate_limited_until > time.time() + + def is_available(self) -> bool: + return self.valid and not self.is_rate_limited() + + def next_available_at(self) -> float: + min_interval = max(0, settings.ACCOUNT_MIN_INTERVAL_MS) / 1000.0 + return max(self.rate_limited_until, self.last_request_started + min_interval) + + def get_status_code(self) -> str: + if self.activation_pending: + return "pending_activation" + if self.is_rate_limited(): + return "rate_limited" + if self.valid: + return "valid" + if self.status_code == "banned": + return "banned" + if self.status_code == "auth_error": + return "auth_error" + return self.status_code or "invalid" + + def get_status_text(self) -> str: + status_map = { + "valid": "正常", + "pending_activation": "待激活", + "rate_limited": "限流", + "banned": "封禁", + "auth_error": "鉴权失败", + "invalid": "失效", + "unknown": "未知", + } + return status_map.get(self.get_status_code(), "未知") + + def to_dict(self): + return { + "email": self.email, + "password": self.password, + "token": self.token, + "cookies": self.cookies, + "username": self.username, + "activation_pending": self.activation_pending, + "status_code": self.status_code, + "last_error": self.last_error, + "last_request_started": self.last_request_started, + "last_request_finished": self.last_request_finished, + "consecutive_failures": self.consecutive_failures, + "rate_limit_strikes": self.rate_limit_strikes, + } + + +class AccountPool: + def __init__(self, db: AsyncJsonDB, max_inflight: int = settings.MAX_INFLIGHT_PER_ACCOUNT): + self.db = db + self.max_inflight = max_inflight + self.accounts: list[Account] = [] + self._lock = asyncio.Lock() + self._waiters: list[asyncio.Event] = [] + self._sticky_email: Optional[str] = None + + async def load(self): + data = await self.db.load() + self.accounts = [Account(**d) for d in data] if isinstance(data, list) else [] + log.info(f"Loaded {len(self.accounts)} upstream account(s)") + + async def save(self): + await self.db.save([a.to_dict() for a in self.accounts]) + + async def add(self, account: Account): + async with self._lock: + self.accounts = [a for a in self.accounts if a.email != account.email] + self.accounts.append(account) + await self.save() + + async def remove(self, email: str): + async with self._lock: + self.accounts = [a for a in self.accounts if a.email != email] + await self.save() + + def set_max_inflight(self, value: int): + self.max_inflight = max(1, int(value)) + + def get_by_email(self, email: str) -> Optional[Account]: + return next((a for a in self.accounts if a.email == email), None) + + async def acquire_preferred(self, preferred_email: str | None = None, exclude: set = None) -> Optional[Account]: + if not preferred_email: + return await self.acquire(exclude) + async with self._lock: + now = time.time() + preferred = next((a for a in self.accounts if a.email == preferred_email), None) + if preferred and preferred.is_available() and preferred.inflight < self.max_inflight and preferred.next_available_at() <= now and (not exclude or preferred.email not in exclude): + preferred.inflight += 1 + preferred.last_used = now + preferred.last_request_started = now + _jitter_seconds() + self._sticky_email = preferred.email + return preferred + return await self.acquire(exclude) + + async def acquire_wait_preferred(self, preferred_email: str | None = None, timeout: float = 60, exclude: set = None) -> Optional[Account]: + deadline = time.time() + timeout + while True: + acc = await self.acquire_preferred(preferred_email, exclude) + if acc: + return acc + remaining = deadline - time.time() + if remaining <= 0: + return None + evt = asyncio.Event() + self._waiters.append(evt) + try: + await asyncio.wait_for(evt.wait(), timeout=min(remaining, 0.5)) + except asyncio.TimeoutError: + pass + finally: + if evt in self._waiters: + self._waiters.remove(evt) + + async def acquire(self, exclude: set = None) -> Optional[Account]: + async with self._lock: + now = time.time() + available = [a for a in self.accounts if a.is_available() and (not exclude or a.email not in exclude)] + if not available: + return None + + ready = [a for a in available if a.inflight < self.max_inflight and a.next_available_at() <= now] + if not ready: + return None + + ready.sort(key=lambda a: (a.inflight, a.last_request_started or 0.0, a.last_used or 0.0)) + best = ready[0] + best.inflight += 1 + best.last_used = now + best.last_request_started = now + _jitter_seconds() + self._sticky_email = best.email if len(ready) == 1 else None + return best + + async def acquire_wait(self, timeout: float = 60, exclude: set = None) -> Optional[Account]: + deadline = time.time() + timeout + while True: + acc = await self.acquire(exclude) + if acc: + return acc + + async with self._lock: + candidates = [ + a for a in self.accounts + if a.valid and (not exclude or a.email not in exclude) + ] + if not candidates: + return None + next_ready_at = min((a.next_available_at() for a in candidates), default=time.time()) + + remaining = deadline - time.time() + if remaining <= 0: + return None + + evt = asyncio.Event() + self._waiters.append(evt) + wait_timeout = min(remaining, max(0.05, next_ready_at - time.time() + 0.05)) + try: + await asyncio.wait_for(evt.wait(), timeout=wait_timeout) + except asyncio.TimeoutError: + pass + finally: + if evt in self._waiters: + self._waiters.remove(evt) + + def release(self, acc: Account): + acc.inflight = max(0, acc.inflight - 1) + acc.last_request_finished = time.time() + if self._waiters: + evt = self._waiters.pop(0) + evt.set() + + def mark_invalid(self, acc: Account, reason: str = "invalid", error_message: str = ""): + acc.valid = False + acc.status_code = reason or "invalid" + acc.last_error = error_message or acc.last_error + acc.consecutive_failures += 1 + if reason == "pending_activation": + acc.activation_pending = True + if self._sticky_email == acc.email: + self._sticky_email = None + log.warning(f"[账号] {acc.email} 已标记为不可用,状态={acc.status_code}") + + def mark_success(self, acc: Account): + acc.consecutive_failures = 0 + acc.rate_limit_strikes = 0 + if acc.status_code == "rate_limited": + acc.status_code = "valid" + if not acc.activation_pending: + acc.valid = True + + def mark_rate_limited(self, acc: Account, cooldown: int | None = None, error_message: str = ""): + acc.rate_limit_strikes += 1 + base = cooldown if cooldown is not None else settings.RATE_LIMIT_BASE_COOLDOWN + dynamic = min(settings.RATE_LIMIT_MAX_COOLDOWN, int(base * (2 ** max(0, acc.rate_limit_strikes - 1)))) + dynamic += int(_jitter_seconds()) + acc.rate_limited_until = time.time() + dynamic + acc.status_code = "rate_limited" + acc.last_error = error_message or acc.last_error + if self._sticky_email == acc.email: + self._sticky_email = None + log.warning(f"[账号] {acc.email} 已限流冷却 {dynamic} 秒") + + def status(self): + available = [a for a in self.accounts if a.is_available()] + rate_limited = [a for a in self.accounts if a.get_status_code() == "rate_limited"] + invalid = [a for a in self.accounts if a.get_status_code() not in ("valid", "rate_limited")] + activation_pending = [a for a in self.accounts if a.get_status_code() == "pending_activation"] + banned = [a for a in self.accounts if a.get_status_code() == "banned"] + in_use = sum(a.inflight for a in self.accounts) + account_min_interval_ms = getattr(settings, "ACCOUNT_MIN_INTERVAL_MS", 0) + return { + "total": len(self.accounts), + "valid": len(available), + "rate_limited": len(rate_limited), + "invalid": len(invalid), + "activation_pending": len(activation_pending), + "banned": len(banned), + "in_use": in_use, + "max_inflight": self.max_inflight, + "waiting": len(self._waiters), + "account_min_interval_ms": account_min_interval_ms, + } diff --git a/backend/core/browser_engine.py b/backend/core/browser_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd1df7aa7758c01a942ed36271776e3f727ea73 --- /dev/null +++ b/backend/core/browser_engine.py @@ -0,0 +1,58 @@ +import asyncio +import os +from contextlib import asynccontextmanager + +_CAMOUFOX_OPTS = { + "headless": True, + "humanize": False, + "i_know_what_im_doing": True, + "firefox_user_prefs": { + "layers.acceleration.disabled": True, + "gfx.webrender.enabled": False, + "gfx.webrender.all": False, + "gfx.webrender.software": False, + "gfx.canvas.azure.backends": "skia", + "media.hardware-video-decoding.enabled": False, + }, +} + + +@asynccontextmanager +async def _new_browser(): + from camoufox.async_api import AsyncCamoufox + + async with AsyncCamoufox(**_CAMOUFOX_OPTS) as browser: + yield browser + + +async def ensure_browser_installed(): + import subprocess + import sys + + try: + result = await asyncio.get_event_loop().run_in_executor( + None, + lambda: subprocess.run( + [sys.executable, "-m", "camoufox", "path"], + capture_output=True, + text=True, + timeout=10, + ), + ) + cache_dir = result.stdout.strip() + if cache_dir: + exe_name = "camoufox.exe" if os.name == "nt" else "camoufox" + exe_path = os.path.join(cache_dir, exe_name) + if os.path.exists(exe_path): + return + except Exception: + pass + + loop = asyncio.get_event_loop() + + def _do_install(): + from camoufox.pkgman import CamoufoxFetcher + + CamoufoxFetcher().install() + + await loop.run_in_executor(None, _do_install) diff --git a/backend/core/config.py b/backend/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..2708d684e61455283481581601e8b89eb605207b --- /dev/null +++ b/backend/core/config.py @@ -0,0 +1,138 @@ +import os +import json +from pathlib import Path +from pydantic_settings import BaseSettings +from typing import Dict, Set + +BASE_DIR = Path(__file__).resolve().parent.parent.parent +DATA_DIR = BASE_DIR / "data" + +class Settings(BaseSettings): + # 服务配置 + PORT: int = int(os.getenv("PORT", 8080)) + WORKERS: int = int(os.getenv("WORKERS", 3)) + ADMIN_KEY: str = os.getenv("ADMIN_KEY", "admin") + + # 并发配置(浏览器仅用于账号注册,不用于对话请求) + BROWSER_POOL_SIZE: int = int(os.getenv("BROWSER_POOL_SIZE", 1)) + MAX_INFLIGHT_PER_ACCOUNT: int = int(os.getenv("MAX_INFLIGHT", 2)) + BROWSER_STREAM_TIMEOUT_SECONDS: int = int(os.getenv("BROWSER_STREAM_TIMEOUT_SECONDS", 1800)) + + # 容灾与限流 + MAX_RETRIES: int = 3 + RATE_LIMIT_COOLDOWN: int = 600 + ACCOUNT_MIN_INTERVAL_MS: int = int(os.getenv("ACCOUNT_MIN_INTERVAL_MS", 0)) + REQUEST_JITTER_MIN_MS: int = int(os.getenv("REQUEST_JITTER_MIN_MS", 0)) + REQUEST_JITTER_MAX_MS: int = int(os.getenv("REQUEST_JITTER_MAX_MS", 0)) + RATE_LIMIT_BASE_COOLDOWN: int = int(os.getenv("RATE_LIMIT_BASE_COOLDOWN", 600)) + RATE_LIMIT_MAX_COOLDOWN: int = int(os.getenv("RATE_LIMIT_MAX_COOLDOWN", 3600)) + + # 日志 + LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO") + + # 数据文件路径 + ACCOUNTS_FILE: str = os.getenv("ACCOUNTS_FILE", str(DATA_DIR / "accounts.json")) + USERS_FILE: str = os.getenv("USERS_FILE", str(DATA_DIR / "users.json")) + CAPTURES_FILE: str = os.getenv("CAPTURES_FILE", str(DATA_DIR / "captures.json")) + CONFIG_FILE: str = os.getenv("CONFIG_FILE", str(DATA_DIR / "config.json")) + + # ????? / ???? + CONTEXT_INLINE_MAX_CHARS: int = int(os.getenv("CONTEXT_INLINE_MAX_CHARS", 4000)) + CONTEXT_FORCE_FILE_MAX_CHARS: int = int(os.getenv("CONTEXT_FORCE_FILE_MAX_CHARS", 10000)) + CONTEXT_ATTACHMENT_TTL_SECONDS: int = int(os.getenv("CONTEXT_ATTACHMENT_TTL_SECONDS", 1800)) + CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS: int = int(os.getenv("CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS", 60)) + CONTEXT_GENERATED_DIR: str = os.getenv("CONTEXT_GENERATED_DIR", str(DATA_DIR / "context_files")) + CONTEXT_CACHE_FILE: str = os.getenv("CONTEXT_CACHE_FILE", str(DATA_DIR / "context_cache.json")) + UPLOADED_FILES_FILE: str = os.getenv("UPLOADED_FILES_FILE", str(DATA_DIR / "uploaded_files.json")) + CONTEXT_AFFINITY_FILE: str = os.getenv("CONTEXT_AFFINITY_FILE", str(DATA_DIR / "session_affinity.json")) + CONTEXT_ALLOWED_GENERATED_EXTS: str = os.getenv("CONTEXT_ALLOWED_GENERATED_EXTS", "txt,md,json,log") + CONTEXT_ALLOWED_USER_EXTS: str = os.getenv("CONTEXT_ALLOWED_USER_EXTS", "txt,md,json,log,xml,yaml,yml,csv,html,css,py,js,ts,java,c,cpp,cs,php,go,rb,sh,zsh,ps1,bat,cmd,pdf,doc,docx,ppt,pptx,xls,xlsx,png,jpg,jpeg,webp,gif,tiff,bmp,svg") + + class Config: + env_file = ".env" + +API_KEYS_FILE = DATA_DIR / "api_keys.json" + +def load_api_keys() -> set: + if API_KEYS_FILE.exists(): + try: + with open(API_KEYS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return set(data.get("keys", [])) + except Exception: + pass + return set() + +def save_api_keys(keys: set): + API_KEYS_FILE.parent.mkdir(parents=True, exist_ok=True) + with open(API_KEYS_FILE, "w", encoding="utf-8") as f: + json.dump({"keys": list(keys)}, f, indent=2) + +# 在内存中存储管理的 API Keys +API_KEYS = load_api_keys() + +VERSION = "2.0.0" + +settings = Settings() + +# 全局映射 +MODEL_MAP = { + # OpenAI (legacy) + "gpt-4o": "qwen3.6-plus", + "gpt-4o-mini": "qwen3.5-flash", + "gpt-4-turbo": "qwen3.6-plus", + "gpt-4": "qwen3.6-plus", + "gpt-4.1": "qwen3.6-plus", + "gpt-4.1-mini": "qwen3.5-flash", + "gpt-3.5-turbo": "qwen3.5-flash", + "gpt-5": "qwen3.7-max", + "o1": "qwen3.6-plus", + "o1-mini": "qwen3.5-flash", + "o3": "qwen3.7-max", + "o3-mini": "qwen3.5-flash", + # OpenAI (2026 latest — point to Qwen3.7-Max for agent workloads) + "gpt-5.5": "qwen3.7-max", + "gpt-5.5-mini": "qwen3.6-plus", + "gpt-5-codex": "qwen3.7-max", + "gpt-5.5-codex": "qwen3.7-max", + "o4": "qwen3.7-max", + "o4-mini": "qwen3.6-plus", + # Anthropic (legacy) + "claude-opus-4-6": "qwen3.6-plus", + "claude-sonnet-4-5": "qwen3.6-plus", + "claude-3-opus": "qwen3.6-plus", + "claude-3.5-sonnet": "qwen3.6-plus", + "claude-3-sonnet": "qwen3.6-plus", + "claude-3-haiku": "qwen3.5-flash", + # Anthropic (2026 latest — Claude Code default models) + "claude-opus-4-7": "qwen3.7-max", + "claude-sonnet-4-6": "qwen3.7-max", + "claude-haiku-4-5": "qwen3.6-plus", + # Gemini (legacy) + "gemini-2.5-pro": "qwen3.6-plus", + "gemini-2.5-flash": "qwen3.5-flash", + # Gemini (2026 latest) + "gemini-3-pro": "qwen3.7-max", + "gemini-3-flash": "qwen3.6-plus", + # Qwen aliases + "qwen": "qwen3.7-max", + "qwen-max": "qwen3.7-max", + "qwen-plus": "qwen3.6-plus", + "qwen-turbo": "qwen3.5-flash", + "qwen-max-preview": "qwen3.7-max", + "qwen3.7-max-preview": "qwen3.7-max", + "qwen3.7-plus": "qwen3.7-plus", + # Qwen 3.8 (upstream preview) + "qwen3.8-max-preview": "qwen3.8-max-preview", + "qwen3.8-max": "qwen3.8-max-preview", + "qwen3.8": "qwen3.8-max-preview", + "qwen-3.8": "qwen3.8-max-preview", + # DeepSeek + "deepseek-chat": "qwen3.6-plus", + "deepseek-reasoner": "qwen3.7-max", + "deepseek-v4": "qwen3.7-max", + "deepseek-v4-flash": "qwen3.6-plus", +} + +def resolve_model(name: str) -> str: + return MODEL_MAP.get(name, name) diff --git a/backend/core/database.py b/backend/core/database.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2c19dcd109c118b510d7eea4f150c73fc55c5c --- /dev/null +++ b/backend/core/database.py @@ -0,0 +1,48 @@ +import asyncio +import json +import logging +from pathlib import Path +from typing import Any, Dict, List, Optional + +log = logging.getLogger("qwen2api.db") + +class AsyncJsonDB: + """带异步读写锁的 JSON 文件存储,防止并发损坏。""" + def __init__(self, path: str | Path, default_data: Any = None): + self.path = Path(path) + self.default_data = default_data if default_data is not None else [] + self._lock = asyncio.Lock() + self._data: Any = None + self._init_file() + + def _init_file(self): + if not self.path.exists(): + self.path.parent.mkdir(parents=True, exist_ok=True) + self.path.write_text(json.dumps(self.default_data, indent=2, ensure_ascii=False), encoding="utf-8") + + async def load(self) -> Any: + async with self._lock: + if not self.path.exists(): + self._data = self.default_data + return self._data + try: + # 为了不阻塞事件循环,本应用可使用 asyncio.to_thread 或者直接读,因为文件很小 + content = self.path.read_text(encoding="utf-8") + self._data = json.loads(content) + except Exception as e: + log.error(f"Failed to load JSON from {self.path}: {e}") + self._data = self.default_data + return self._data + + async def save(self, data: Any): + async with self._lock: + self._data = data + try: + self.path.write_text(json.dumps(self._data, indent=2, ensure_ascii=False), encoding="utf-8") + except Exception as e: + log.error(f"Failed to save JSON to {self.path}: {e}") + + async def get(self) -> Any: + if self._data is None: + return await self.load() + return self._data diff --git a/backend/core/httpx_engine.py b/backend/core/httpx_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..e19c0e39e250dab8edd6d462e8a79c41713749e4 --- /dev/null +++ b/backend/core/httpx_engine.py @@ -0,0 +1,135 @@ +""" +httpx_engine.py — 用 curl_cffi 直连 Qwen API(Chrome TLS 指纹) +优点:TLS 指纹与真实 Chrome 一致,无编码问题,支持流式早期中止 +优化:使用全局连接池,避免频繁 TLS 握手 +""" + +import asyncio +import json +import logging +from curl_cffi.requests import AsyncSession + +log = logging.getLogger("qwen2api.httpx_engine") + +BASE_URL = "https://chat.qwen.ai" + +_HEADERS = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", + "Accept": "application/json, text/plain, */*", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Referer": "https://chat.qwen.ai/", + "Origin": "https://chat.qwen.ai", + "sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"', + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": '"Windows"', + "sec-fetch-dest": "empty", + "sec-fetch-mode": "cors", + "sec-fetch-site": "same-origin", +} + +_IMPERSONATE = "chrome124" + +# ✅ 全局连接池(避免频繁 TLS 握手) +_global_session: AsyncSession = None +_session_lock: asyncio.Lock = None + + +async def _get_global_session() -> AsyncSession: + """获取全局 AsyncSession""" + global _global_session, _session_lock + + if _session_lock is None: + _session_lock = asyncio.Lock() + + if _global_session is not None: + return _global_session + + async with _session_lock: + if _global_session is not None: + return _global_session + + _global_session = AsyncSession(impersonate=_IMPERSONATE, timeout=30) + log.info("[HttpxEngine] ✅ 全局连接池已初始化") + return _global_session + + +async def _close_global_session(): + """关闭全局 session""" + global _global_session + if _global_session: + try: + await _global_session.close() + log.info("[HttpxEngine] ✅ 全局连接池已关闭") + except Exception as e: + log.error(f"[HttpxEngine] 关闭连接池失败: {e}") + finally: + _global_session = None + + +class HttpxEngine: + """Direct curl_cffi engine — Chrome TLS fingerprint, same interface as BrowserEngine.""" + + def __init__(self, pool_size: int = 3, base_url: str = BASE_URL): + self.base_url = base_url + self._started = False + self._ready = asyncio.Event() + + async def start(self): + # ✅ 初始化全局连接池 + await _get_global_session() + self._started = True + self._ready.set() + log.info("[HttpxEngine] 已启动(curl_cffi Chrome指纹直连模式 + 全局连接池)") + + async def stop(self): + self._started = False + # ✅ 关闭全局连接池 + await _close_global_session() + log.info("[HttpxEngine] 已停止") + + def _auth_headers(self, token: str) -> dict: + return {**_HEADERS, "Authorization": f"Bearer {token}"} + + async def api_call(self, method: str, path: str, token: str, body: dict = None) -> dict: + # ✅ 改进:使用全局 session 而不是创建新的 + url = self.base_url + path + headers = {**self._auth_headers(token), "Content-Type": "application/json"} + data = json.dumps(body, ensure_ascii=False).encode() if body else None + try: + session = await _get_global_session() + resp = await session.request(method, url, headers=headers, data=data) + return {"status": resp.status_code, "body": resp.text} + except Exception as e: + log.error(f"[HttpxEngine] api_call error: {e}") + return {"status": 0, "body": str(e)} + + async def fetch_chat(self, token: str, chat_id: str, payload: dict, buffered: bool = False): + """Stream Qwen SSE via curl_cffi with Chrome TLS fingerprint (with global connection pool).""" + # ✅ 改进:使用全局 session 而不是创建新的 + url = self.base_url + f"/api/v2/chat/completions?chat_id={chat_id}" + headers = { + **self._auth_headers(token), + "Content-Type": "application/json", + "Accept": "text/event-stream", + } + body_bytes = json.dumps(payload, ensure_ascii=False).encode() + + try: + session = await _get_global_session() + async with session.stream("POST", url, headers=headers, data=body_bytes) as resp: + if resp.status_code != 200: + body_chunks = [] + async for chunk in resp.aiter_content(): + body_chunks.append(chunk) + body_text = b"".join(body_chunks).decode(errors="replace")[:2000] + yield {"status": resp.status_code, "body": body_text} + return + + async for chunk in resp.aiter_content(): + decoded = chunk.decode("utf-8", errors="replace") + yield {"status": "streamed", "chunk": decoded} + + except Exception as e: + log.error(f"[HttpxEngine] fetch_chat error: {e}") + yield {"status": 0, "body": str(e)} + diff --git a/backend/core/hybrid_engine.py b/backend/core/hybrid_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a63d257b0a1c54d32d1bbf219e9510e01625e2 --- /dev/null +++ b/backend/core/hybrid_engine.py @@ -0,0 +1,122 @@ +""" +hybrid_engine.py — mix browser stability with httpx speed. +Phase 1 policy: +- api_call: httpx first, browser fallback on failures +- fetch_chat: browser first (real browser TLS/env), httpx fallback on browser failures +""" + +import logging + +log = logging.getLogger("qwen2api.hybrid_engine") + + +class HybridEngine: + def __init__(self, browser_engine, httpx_engine): + self.browser_engine = browser_engine + self.httpx_engine = httpx_engine + self._started = False + self.base_url = getattr(browser_engine, "base_url", getattr(httpx_engine, "base_url", "https://chat.qwen.ai")) + self.pool_size = getattr(browser_engine, "pool_size", 0) + self._pages = getattr(browser_engine, "_pages", None) + + async def start(self): + log.info("[HybridEngine] 启动开始:先启动 httpx 引擎") + await self.httpx_engine.start() + log.info("[HybridEngine] 第一步完成:httpx 已启动,继续启动浏览器引擎") + await self.browser_engine.start() + self._started = bool(getattr(self.httpx_engine, "_started", False) and getattr(self.browser_engine, "_started", False)) + log.info(f"[HybridEngine] 已启动:api_call=httpx优先,fetch_chat=browser优先,started={self._started} browser_started={getattr(self.browser_engine, '_started', False)} httpx_started={getattr(self.httpx_engine, '_started', False)}") + + async def stop(self): + try: + await self.httpx_engine.stop() + finally: + await self.browser_engine.stop() + self._started = False + log.info("[HybridEngine] 已停止") + + async def api_call(self, method: str, path: str, token: str, body: dict = None) -> dict: + log.info(f"[HybridEngine] api_call 路由:优先走 httpx,method={method} path={path}") + result = await self.httpx_engine.api_call(method, path, token, body) + status = result.get("status") + body_text = (result.get("body") or "").lower() + should_fallback = ( + status == 0 + or status in (401, 403, 429) + or "waf" in body_text + or " dict: + free_pages = 0 + queue = 0 + if self._pages is not None: + try: + free_pages = self._pages.qsize() + queue = max(0, self.pool_size - free_pages) + except Exception: + free_pages = 0 + queue = 0 + return { + "started": self._started, + "mode": "hybrid", + "stream_via": "browser_first", + "api_via": "httpx_first", + "browser_started": getattr(self.browser_engine, "_started", False), + "httpx_started": getattr(self.httpx_engine, "_started", False), + "pool_size": self.pool_size, + "free_pages": free_pages, + "queue": queue, + } diff --git a/backend/core/log_filter.py b/backend/core/log_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..56fc6ab4fc00cb022b683a811c9f0fb5d1f37836 --- /dev/null +++ b/backend/core/log_filter.py @@ -0,0 +1,134 @@ +"""日志过滤器 - 精简和中文化日志输出""" +import logging +import re + + +class SimplifiedLogFilter(logging.Filter): + """精简日志过滤器 - 移除冗余信息""" + + # 需要完全过滤的日志模式 + SKIP_PATTERNS = [ + r"HTTP Request: POST https://chat\.qwen\.ai", + r"HTTP Request: GET https://chat\.qwen\.ai", + r"HTTP Request: DELETE https://chat\.qwen\.ai", + r"\[ToolParse\].*原始回复", + r"prompt preview \(first \d+ chars\)", + r"feature_config:", + r"prompt contains ##TOOL_CALL##", + ] + + # 需要简化的日志模式(保留但精简) + SIMPLIFY_PATTERNS = { + r"\[SessionPlan\] surface=\S+ enabled=(\S+) reuse_chat=(\S+) reason=(\S+).*": + r"会话计划: 启用=\1 复用=\2 原因=\3", + + r"\[Executor\] acquired account=(\S+) model=(\S+) attempt=(\d+)": + r"获取账号: \1 模型=\2 尝试=\3", + + r"\[Executor\] created chat_id=(\S+) account=(\S+)": + r"创建会话: \1 账号=\2", + + r"\[Executor\] stream start chat_id=(\S+) model=(\S+)": + r"开始流式: 会话=\1 模型=\2", + + r"\[Executor\] stream finish chat_id=(\S+) total=([\d.]+)s": + r"完成流式: 会话=\1 耗时=\2秒", + + r"\[Executor\] first parsed event after ([\d.]+)s chat_id=(\S+)": + r"首次响应: \1秒 会话=\2", + + r"\[Collect\] ✓ Tool Sieve 刷新检测到工具调用: tools=\[([^\]]+)\]": + r"检测到工具: \1", + + r"\[Collect\] finalize reason=(\S+) chat_id=(\S+) tool_calls=(\d+)": + r"完成收集: 原因=\1 工具数=\3", + + r"\[ANT\] model=(\S+), stream=(\S+), tool_enabled=(\S+)": + r"请求配置: 模型=\1 流式=\2 工具=\3", + } + + def filter(self, record: logging.LogRecord) -> bool: + msg = record.getMessage() + + # 检查是否需要完全过滤 + for pattern in self.SKIP_PATTERNS: + if re.search(pattern, msg): + return False + + # 检查是否需要简化 + for pattern, replacement in self.SIMPLIFY_PATTERNS.items(): + match = re.search(pattern, msg) + if match: + record.msg = re.sub(pattern, replacement, msg) + record.args = () + break + + return True + + +class ChineseLogFilter(logging.Filter): + """中文化日志过滤器 - 将英文日志转换为中文""" + + TRANSLATIONS = { + # 启动/关闭 + "Starting": "启动中", + "Shutting down": "关闭中", + "Startup complete": "启动完成", + + # 账号相关 + "Account": "账号", + "account": "账号", + "token": "令牌", + "Token": "令牌", + + # 请求相关 + "Request": "请求", + "request": "请求", + "Response": "响应", + "response": "响应", + + # 模型相关 + "model": "模型", + "Model": "模型", + + # 工具相关 + "tool": "工具", + "Tool": "工具", + "tools": "工具", + "Tools": "工具", + + # 状态 + "success": "成功", + "Success": "成功", + "failed": "失败", + "Failed": "失败", + "error": "错误", + "Error": "错误", + "warning": "警告", + "Warning": "警告", + + # 动作 + "created": "已创建", + "Created": "已创建", + "deleted": "已删除", + "Deleted": "已删除", + "updated": "已更新", + "Updated": "已更新", + } + + def filter(self, record: logging.LogRecord) -> bool: + msg = record.getMessage() + + # 简单替换(仅替换独立单词) + for en, zh in self.TRANSLATIONS.items(): + msg = re.sub(rf'\b{en}\b', zh, msg) + + record.msg = msg + record.args = () + return True + + +def apply_log_filters(logger: logging.Logger) -> None: + """应用日志过滤器到指定 logger""" + logger.addFilter(SimplifiedLogFilter()) + # logger.addFilter(ChineseLogFilter()) # 可选:启用中文化 diff --git a/backend/core/request_logging.py b/backend/core/request_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..2010a3e03998edfbbf220a11e9c3f2fb3605de5a --- /dev/null +++ b/backend/core/request_logging.py @@ -0,0 +1,98 @@ +import contextvars +import logging +import uuid +from contextlib import contextmanager +from typing import Any + +_REQUEST_CONTEXT: contextvars.ContextVar[dict[str, Any]] = contextvars.ContextVar( + "request_context", default={} +) + +_REQUEST_DEFAULTS: dict[str, Any] = { + "req_id": "-", + "surface": "-", + "requested_model": "-", + "resolved_model": "-", + "chat_id": "-", + "stream_attempt": "-", + "upstream_attempt": "-", +} + +_LOG_FORMAT = ( + "%(asctime)s [%(levelname)s] %(message)s" +) + + +class RequestContextFilter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + ctx = get_request_context() + for key, default in _REQUEST_DEFAULTS.items(): + setattr(record, key, ctx.get(key, default)) + return True + + +request_context_filter = RequestContextFilter() + + +class SafeRequestFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + for key, default in _REQUEST_DEFAULTS.items(): + if not hasattr(record, key): + setattr(record, key, default) + return super().format(record) + + +def configure_logging(level: int = logging.INFO) -> None: + root = logging.getLogger() + root.setLevel(level) + + # 应用精简日志过滤器 + try: + from backend.core.log_filter import SimplifiedLogFilter + if not any(isinstance(f, SimplifiedLogFilter) for f in root.filters): + root.addFilter(SimplifiedLogFilter()) + except ImportError: + pass + + formatter = SafeRequestFormatter(_LOG_FORMAT) + + if not root.handlers: + handler = logging.StreamHandler() + handler.setLevel(level) + handler.setFormatter(formatter) + root.addHandler(handler) + return + + for handler in root.handlers: + handler.setLevel(level) + handler.setFormatter(formatter) + + +def new_request_id() -> str: + return uuid.uuid4().hex[:8] + + +def get_request_context() -> dict[str, Any]: + ctx = dict(_REQUEST_DEFAULTS) + ctx.update(_REQUEST_CONTEXT.get({})) + return ctx + + +def update_request_context(**kwargs: Any) -> dict[str, Any]: + ctx = get_request_context() + for key, value in kwargs.items(): + if value is not None: + ctx[key] = value + _REQUEST_CONTEXT.set(ctx) + return ctx + + +@contextmanager +def request_context(**kwargs: Any): + merged = get_request_context() + merged.update({k: v for k, v in kwargs.items() if v is not None}) + token = _REQUEST_CONTEXT.set(merged) + try: + yield _REQUEST_CONTEXT.get({}) + finally: + _REQUEST_CONTEXT.reset(token) diff --git a/backend/core/session_affinity.py b/backend/core/session_affinity.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee56ab659babf923c6dbb2f41467b1d4a8956d4 --- /dev/null +++ b/backend/core/session_affinity.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import time +from dataclasses import dataclass, field +from typing import Any + +from backend.core.database import AsyncJsonDB + + +@dataclass(slots=True) +class SessionAffinityRecord: + session_key: str + surface: str + account_email: str + uploaded_files: list[dict[str, Any]] = field(default_factory=list) + chat_id: str | None = None + message_hashes: list[str] = field(default_factory=list) + updated_at: float = 0.0 + expires_at: float = 0.0 + + def to_dict(self) -> dict[str, Any]: + return { + "session_key": self.session_key, + "surface": self.surface, + "account_email": self.account_email, + "uploaded_files": self.uploaded_files, + "chat_id": self.chat_id, + "message_hashes": self.message_hashes, + "updated_at": self.updated_at, + "expires_at": self.expires_at, + } + + +class SessionAffinityStore: + def __init__(self, db: AsyncJsonDB): + self.db = db + self.records: dict[str, SessionAffinityRecord] = {} + + @staticmethod + def _from_item(item: dict[str, Any]) -> SessionAffinityRecord | None: + if not isinstance(item, dict) or not item.get("session_key"): + return None + return SessionAffinityRecord( + session_key=str(item.get("session_key") or ""), + surface=str(item.get("surface") or ""), + account_email=str(item.get("account_email") or ""), + uploaded_files=list(item.get("uploaded_files") or []), + chat_id=(str(item.get("chat_id")) if item.get("chat_id") else None), + message_hashes=[str(v) for v in (item.get("message_hashes") or []) if str(v)], + updated_at=float(item.get("updated_at") or 0.0), + expires_at=float(item.get("expires_at") or 0.0), + ) + + async def load(self): + data = await self.db.load() + self.records = {} + if isinstance(data, list): + for item in data: + rec = self._from_item(item) + if rec is None: + continue + self.records[rec.session_key] = rec + + async def save(self): + await self.db.save([record.to_dict() for record in self.records.values()]) + + async def get(self, session_key: str) -> SessionAffinityRecord | None: + if not self.records: + await self.load() + record = self.records.get(session_key) + if record and record.expires_at and record.expires_at < time.time(): + self.records.pop(session_key, None) + await self.save() + return None + return record + + async def bind_account(self, session_key: str, surface: str, account_email: str, ttl_seconds: int) -> SessionAffinityRecord: + now = time.time() + record = self.records.get(session_key) + if record is None: + record = SessionAffinityRecord(session_key=session_key, surface=surface, account_email=account_email) + record.surface = surface + record.account_email = account_email + record.updated_at = now + record.expires_at = now + max(60, ttl_seconds) + self.records[session_key] = record + await self.save() + return record + + async def bind_chat( + self, + session_key: str, + *, + surface: str, + account_email: str, + chat_id: str, + message_hashes: list[str], + ttl_seconds: int, + ) -> SessionAffinityRecord: + now = time.time() + record = self.records.get(session_key) + if record is None: + record = SessionAffinityRecord(session_key=session_key, surface=surface, account_email=account_email) + record.surface = surface + record.account_email = account_email + record.chat_id = chat_id + record.message_hashes = list(message_hashes) + record.updated_at = now + record.expires_at = now + max(60, ttl_seconds) + self.records[session_key] = record + await self.save() + return record + + async def clear_chat(self, session_key: str) -> None: + record = await self.get(session_key) + if record is None: + return + record.chat_id = None + record.message_hashes = [] + record.updated_at = time.time() + self.records[session_key] = record + await self.save() + + async def add_uploaded_file(self, session_key: str, file_meta: dict[str, Any]) -> None: + record = await self.get(session_key) + if record is None: + return + record.uploaded_files.append(file_meta) + record.updated_at = time.time() + self.records[session_key] = record + await self.save() + + async def clear(self, session_key: str) -> None: + self.records.pop(session_key, None) + await self.save() + + def active_chat_ids(self) -> set[str]: + now = time.time() + return { + record.chat_id + for record in self.records.values() + if record.chat_id and (not record.expires_at or record.expires_at >= now) + } + + async def cleanup_expired(self) -> list[SessionAffinityRecord]: + now = time.time() + expired_keys = [key for key, record in self.records.items() if record.expires_at and record.expires_at < now] + expired_records = [self.records[key] for key in expired_keys] + for key in expired_keys: + self.records.pop(key, None) + if expired_keys: + await self.save() + return expired_records diff --git a/backend/core/session_lock.py b/backend/core/session_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..2f96f23773b59038333267f2863fb3592f2ba393 --- /dev/null +++ b/backend/core/session_lock.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import asyncio +from contextlib import asynccontextmanager + + +class SessionLockRegistry: + def __init__(self): + self._locks: dict[str, asyncio.Lock] = {} + self._refs: dict[str, int] = {} + self._guard = asyncio.Lock() + + async def _get_lock(self, session_key: str) -> asyncio.Lock: + async with self._guard: + lock = self._locks.get(session_key) + if lock is None: + lock = asyncio.Lock() + self._locks[session_key] = lock + self._refs[session_key] = 0 + self._refs[session_key] = self._refs.get(session_key, 0) + 1 + return lock + + async def _release_ref(self, session_key: str) -> None: + async with self._guard: + if session_key not in self._refs: + return + self._refs[session_key] = max(0, self._refs[session_key] - 1) + if self._refs[session_key] == 0: + self._refs.pop(session_key, None) + self._locks.pop(session_key, None) + + @asynccontextmanager + async def hold(self, session_key: str): + lock = await self._get_lock(session_key) + await lock.acquire() + try: + yield + finally: + lock.release() + await self._release_ref(session_key) diff --git a/backend/core/tool_cache.py b/backend/core/tool_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea650fb26c85576cf3448218078d309273ab042 --- /dev/null +++ b/backend/core/tool_cache.py @@ -0,0 +1,102 @@ +""" +工具调用缓存 - 避免重复执行相同工具调用 +预期收益: 相同工具调用 -97%, 减少API调用 + +关键特性: +- SHA256 哈希为缓存键 +- TTL 过期机制 +- 线程安全 +""" + +import hashlib +import json +import time +import logging +from typing import Dict, Any, Optional, Tuple + +log = logging.getLogger("qwen2api.tool_cache") + + +class ToolCallCache: + """工具调用结果缓存""" + + def __init__(self, ttl_seconds: int = 300): + self.ttl = ttl_seconds + self.cache: Dict[str, Tuple[Any, float]] = {} + self.stats = { + "hits": 0, + "misses": 0, + "sets": 0, + } + + def _make_key(self, tool_name: str, tool_input: Dict[str, Any]) -> str: + """生成工具调用缓存键""" + try: + serialized = json.dumps(tool_input, sort_keys=True, ensure_ascii=False) + except (TypeError, ValueError): + serialized = str(tool_input) + + hash_val = hashlib.sha256(serialized.encode()).hexdigest()[:16] + return f"{tool_name}:{hash_val}" + + def get(self, tool_name: str, tool_input: Dict[str, Any]) -> Optional[Any]: + """获取缓存的工具结果""" + key = self._make_key(tool_name, tool_input) + + if key not in self.cache: + self.stats["misses"] += 1 + return None + + result, cached_at = self.cache[key] + + # 检查过期 + if time.time() - cached_at > self.ttl: + del self.cache[key] + self.stats["misses"] += 1 + return None + + self.stats["hits"] += 1 + log.info(f"[ToolCache-HIT] {tool_name}: {key}") + return result + + def set(self, tool_name: str, tool_input: Dict[str, Any], result: Any): + """缓存工具调用结果""" + key = self._make_key(tool_name, tool_input) + self.cache[key] = (result, time.time()) + self.stats["sets"] += 1 + log.debug(f"[ToolCache-SET] {tool_name}: {key}") + + def clear(self): + """清空缓存""" + self.cache.clear() + log.info("[ToolCache] 已清空缓存") + + def cleanup_expired(self): + """清理过期缓存""" + now = time.time() + expired = [k for k, (_, t) in self.cache.items() if now - t > self.ttl] + for k in expired: + del self.cache[k] + if expired: + log.debug(f"[ToolCache] 清理了 {len(expired)} 条过期缓存") + + def status(self) -> Dict[str, Any]: + """缓存统计""" + now = time.time() + active = sum(1 for _, (_, t) in self.cache.items() if now - t < self.ttl) + total_requests = self.stats["hits"] + self.stats["misses"] + hit_rate = self.stats["hits"] / total_requests if total_requests > 0 else 0 + + return { + "total_cached": len(self.cache), + "active": active, + "expired": len(self.cache) - active, + "hits": self.stats["hits"], + "misses": self.stats["misses"], + "hit_rate": f"{hit_rate*100:.1f}%", + "sets": self.stats["sets"], + } + + +# 全局工具缓存实例 +tool_cache = ToolCallCache(ttl_seconds=300) diff --git a/backend/core/upstream_file_cache.py b/backend/core/upstream_file_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..c39777217225bfa54caa5ffc333febd41a67e486 --- /dev/null +++ b/backend/core/upstream_file_cache.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import time +from dataclasses import dataclass +from typing import Any + +from backend.core.database import AsyncJsonDB + + +@dataclass(slots=True) +class UpstreamFileCacheEntry: + session_key: str + account_email: str + sha256: str + ext: str + filename: str + remote_file_meta: dict[str, Any] + created_at: float + expires_at: float + + def to_dict(self) -> dict[str, Any]: + return { + "session_key": self.session_key, + "account_email": self.account_email, + "sha256": self.sha256, + "ext": self.ext, + "filename": self.filename, + "remote_file_meta": self.remote_file_meta, + "created_at": self.created_at, + "expires_at": self.expires_at, + } + + +class UpstreamFileCache: + def __init__(self, db: AsyncJsonDB): + self.db = db + self.entries: list[UpstreamFileCacheEntry] = [] + + async def load(self): + data = await self.db.load() + self.entries = [] + if isinstance(data, list): + for item in data: + if isinstance(item, dict): + self.entries.append(UpstreamFileCacheEntry(**item)) + + async def save(self): + await self.db.save([entry.to_dict() for entry in self.entries]) + + async def get(self, session_key: str, account_email: str, sha256: str, ext: str) -> UpstreamFileCacheEntry | None: + if not self.entries: + await self.load() + now = time.time() + for entry in self.entries: + if entry.expires_at and entry.expires_at < now: + continue + if entry.session_key == session_key and entry.account_email == account_email and entry.sha256 == sha256 and entry.ext == ext: + return entry + return None + + async def set(self, entry: UpstreamFileCacheEntry): + self.entries = [e for e in self.entries if not (e.session_key == entry.session_key and e.account_email == entry.account_email and e.sha256 == entry.sha256 and e.ext == entry.ext)] + self.entries.append(entry) + await self.save() + + async def cleanup_expired(self): + now = time.time() + before = len(self.entries) + self.entries = [entry for entry in self.entries if not entry.expires_at or entry.expires_at >= now] + if len(self.entries) != before: + await self.save() diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000000000000000000000000000000000000..47beb03ffdf2b60c1200ed5306703a5276ff77d8 --- /dev/null +++ b/backend/main.py @@ -0,0 +1,139 @@ +import asyncio +import logging +from contextlib import asynccontextmanager +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles +import os +import sys + +# 将项目根目录加入到 sys.path,解决直接运行 main.py 时找不到 backend 模块的问题 +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from backend.core.config import settings +from backend.core.database import AsyncJsonDB +from backend.core.account_pool import AccountPool +from backend.core.session_affinity import SessionAffinityStore +from backend.core.upstream_file_cache import UpstreamFileCache +from backend.core.session_lock import SessionLockRegistry +from backend.core.request_logging import configure_logging, request_context +from backend.services.qwen_client import QwenClient +from backend.services.file_store import LocalFileStore +from backend.services.context_offload import ContextOffloader +from backend.services.upstream_file_uploader import UpstreamFileUploader +import backend.api.models as models +from backend.api import admin, v1_chat, probes, anthropic, gemini, embeddings, images, videos, files_api +from backend.services.garbage_collector import garbage_collect_chats +from backend.services.context_cleanup import context_cleanup_loop + +configure_logging(getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO)) +log = logging.getLogger("qwen2api") + +@asynccontextmanager +async def lifespan(app: FastAPI): + with request_context(surface="startup"): + log.info("正在启动 qwen2API v2.0 企业网关...") + + # 初始化数据存储 (带锁 JSON) + app.state.accounts_db = AsyncJsonDB(settings.ACCOUNTS_FILE, default_data=[]) + app.state.users_db = AsyncJsonDB(settings.USERS_FILE, default_data=[]) + app.state.captures_db = AsyncJsonDB(settings.CAPTURES_FILE, default_data=[]) + app.state.session_affinity_db = AsyncJsonDB(settings.CONTEXT_AFFINITY_FILE, default_data=[]) + app.state.context_cache_db = AsyncJsonDB(settings.CONTEXT_CACHE_FILE, default_data=[]) + app.state.uploaded_files_db = AsyncJsonDB(settings.UPLOADED_FILES_FILE, default_data=[]) + + # 初始化组件 + app.state.account_pool = AccountPool(app.state.accounts_db, max_inflight=settings.MAX_INFLIGHT_PER_ACCOUNT) + app.state.qwen_client = QwenClient(app.state.account_pool) + app.state.qwen_executor = app.state.qwen_client.executor + app.state.file_store = LocalFileStore(settings.CONTEXT_GENERATED_DIR, app.state.uploaded_files_db) + app.state.session_affinity = SessionAffinityStore(app.state.session_affinity_db) + app.state.upstream_file_cache = UpstreamFileCache(app.state.context_cache_db) + app.state.context_offloader = ContextOffloader(settings) + app.state.upstream_file_uploader = UpstreamFileUploader(app.state.qwen_client, settings) + app.state.session_locks = SessionLockRegistry() + + # 加载账号并启动后台清理任务 + await app.state.account_pool.load() + await app.state.file_store.load() + await app.state.session_affinity.load() + await app.state.upstream_file_cache.load() + asyncio.create_task(garbage_collect_chats(app)) + asyncio.create_task(context_cleanup_loop(app)) + + # 启动 chat_id 预热池(省上游 /chats/new 握手 500ms~6s) + # 注:原默认 target_per_account=5 在 21 账号下,每 30s 触发 ~100 次 + # /chats/new 请求,会被 Qwen 风控降级为空 SSE。这里降到 1 个 + 长 TTL。 + from backend.services.chat_id_pool import ChatIdPool + app.state.chat_id_pool = ChatIdPool(app.state.qwen_client, target_per_account=1, ttl_seconds=1800, default_model="qwen3.6-plus") + app.state.qwen_executor.chat_id_pool = app.state.chat_id_pool # 让 executor 直接访问 + await app.state.chat_id_pool.start() + + yield + + with request_context(surface="shutdown"): + log.info("正在关闭网关服务...") + # 关闭 chat_id 池 + pool = getattr(app.state, "chat_id_pool", None) + if pool: + await pool.stop() + # 关闭 HTTP 连接池 + await app.state.qwen_client._http_client.aclose() + log.info("HTTP 连接池已关闭") + # 持久化 Playwright cookie 并关闭浏览器 + try: + await app.state.qwen_client._save_cookies() + log.info("Playwright cookie 已持久化") + except Exception as e: + log.warning(f"保存 Playwright cookie 失败: {e}") + try: + if app.state.qwen_client._pw_context: + await app.state.qwen_client._pw_context.close() + if app.state.qwen_client._pw_browser: + await app.state.qwen_client._pw_browser.close() + if app.state.qwen_client._pw_playwright: + await app.state.qwen_client._pw_playwright.stop() + log.info("Playwright 浏览器已关闭") + except Exception as e: + log.warning(f"关闭 Playwright 浏览器失败: {e}") + +app = FastAPI(title="qwen2API Enterprise Gateway", version="2.0.0", lifespan=lifespan) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# 挂载路由 +app.include_router(v1_chat.router, tags=["OpenAI Compatible"]) +app.include_router(models.router, tags=["Models"]) +app.include_router(anthropic.router, tags=["Claude Compatible"]) +app.include_router(gemini.router, tags=["Gemini Compatible"]) +app.include_router(embeddings.router, tags=["Embeddings"]) +app.include_router(images.router, tags=["Images"]) +app.include_router(videos.router, tags=["Videos"]) +app.include_router(files_api.router, tags=["Files"]) +app.include_router(probes.router, tags=["Probes"]) +app.include_router(admin.router, prefix="/api/admin", tags=["Dashboard Admin"]) + +@app.get("/api", tags=["System"]) +async def root(): + return { + "status": "qwen2API Enterprise Gateway is running", + "docs": "/docs", + "version": "2.0.0" + } + +# 托管前端构建产物 +FRONTEND_DIST = os.path.join(os.path.dirname(os.path.dirname(__file__)), "frontend", "dist") +if os.path.exists(FRONTEND_DIST): + app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend") +else: + log.warning(f"未找到前端构建目录: {FRONTEND_DIST},WebUI 将不可用。") + +if __name__ == "__main__": + import uvicorn + uvicorn.run("backend.main:app", host="0.0.0.0", port=settings.PORT, workers=1) diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b8ee9260a92eda37dcaa76a944dd8264858a9af --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,10 @@ +fastapi +uvicorn[standard] +httpx[http2] +pydantic-settings +python-dotenv +python-multipart +tiktoken +curl_cffi +camoufox +oss2 diff --git a/backend/runtime/__init__.py b/backend/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8851d4b2f4e0ff8e3ad3aed9dba8d415968659d4 --- /dev/null +++ b/backend/runtime/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from . import stream_presenter + +__all__ = ["stream_presenter"] diff --git a/backend/runtime/attachment_types.py b/backend/runtime/attachment_types.py new file mode 100644 index 0000000000000000000000000000000000000000..c867e612535bbda0029515eb3d263214e710dead --- /dev/null +++ b/backend/runtime/attachment_types.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass(slots=True) +class NormalizedAttachment: + file_id: str + filename: str = "" + content_type: str = "application/octet-stream" + source: str = "upload" + local_path: str = "" + sha256: str = "" + purpose: str = "context" + remote_file_id: str = "" + remote_object_key: str = "" + remote_parse_status: str = "" + remote_ref: dict[str, Any] = field(default_factory=dict) diff --git a/backend/runtime/execution.py b/backend/runtime/execution.py new file mode 100644 index 0000000000000000000000000000000000000000..939fd46a71ea3ebc1106ecd760de676425feff54 --- /dev/null +++ b/backend/runtime/execution.py @@ -0,0 +1,1048 @@ +from __future__ import annotations + +import asyncio +import json +import logging +import re +from dataclasses import dataclass, field +from typing import Any, Awaitable, Callable + +from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE, StandardRequest +from backend.core.config import settings +from backend.core.request_logging import update_request_context +from backend.runtime.stream_metrics import StreamMetrics +from backend.services import tool_parser +from backend.toolcall.normalize import normalize_tool_name +from backend.toolcall.stream_state import StreamingToolCallState + + +# Qwen 偶尔生成的毒性"工具不存在"或"无法继续"幻觉。 +# 在流式收到前 20 字时识别,触发早期拦截 + retry 而不是流给客户端。 +_TOXIC_REFUSAL_RE = re.compile( + # 英文:工具不存在/不可用 + r"Tool\s+\S+\s+(?:does\s+not\s+exists?|is\s+not\s+(?:available|registered))" + r"|I\s+cannot\s+execute\s+this\s+tool" + # 英文:任务放弃/拒绝继续 + r"|I[''\u2019]?\s*m\s+sorry[,. ]" + r"|I\s+cannot\s+(?:help|assist|proceed|continue|support|perform)" + r"|I[''\u2019]?m\s+not\s+(?:able|designed)\s+to" + r"|unable\s+to\s+(?:proceed|continue|perform|complete)" + # 中文:工具/操作不存在或无法继续 + r"|该工具.{0,8}?不存在|工具.{0,12}?不存在" + r"|我(?:无法|不能|不可以)(?:继续|进行|支持|完成|操作|执行)" + r"|无法(?:进行|支持|完成|执行).{0,10}?操作" + r"|抱歉.{0,20}?(?:无法|不能|不支持)", + re.IGNORECASE, +) + + +log = logging.getLogger("qwen2api.runtime") + + +@dataclass(slots=True) +class RuntimeAttemptState: + answer_text: str = "" + reasoning_text: str = "" + tool_calls: list[dict[str, Any]] = field(default_factory=list) + blocked_tool_names: list[str] = field(default_factory=list) + finish_reason: str = "stop" + raw_events: list[dict[str, Any]] = field(default_factory=list) + emitted_visible_output: bool = False + stage_metrics: dict[str, float] = field(default_factory=dict) + + +@dataclass(slots=True) +class RuntimeExecutionResult: + state: RuntimeAttemptState + chat_id: str | None + acc: Any | None + + +@dataclass(slots=True) +class RuntimeToolDirective: + tool_blocks: list[dict[str, Any]] = field(default_factory=list) + stop_reason: str = "end_turn" + + +@dataclass(slots=True) +class RuntimeRetryDirective: + retry: bool + next_prompt: str + reason: str | None = None + + +@dataclass(slots=True) +class RuntimeRetryContinuation: + should_continue: bool + next_prompt: str + + +@dataclass(slots=True) +class RuntimeRetryLoop: + prompt: str + max_attempts: int + + +@dataclass(slots=True) +class RuntimeAttemptPlan: + loop: RuntimeRetryLoop + prompt: str + + +@dataclass(slots=True) +class AnthropicStreamCompletionResult: + chunks: list[str] + + +@dataclass(slots=True) +class AnthropicStreamSuccessResult: + chunks: list[str] + usage_delta: int + + +@dataclass(slots=True) +class RuntimeAttemptOutcome: + execution: RuntimeExecutionResult + continuation: RuntimeRetryContinuation + + +@dataclass(slots=True) +class RuntimeAttemptCursor: + index: int + number: int + + +TRAILING_IDLE_AFTER_TOOL_SECONDS = 2.0 + + +__all__ = [ + "RuntimeAttemptState", + "RuntimeExecutionResult", + "RuntimeToolDirective", + "RuntimeRetryDirective", + "RuntimeRetryContinuation", + "RuntimeRetryLoop", + "RuntimeAttemptPlan", + "AnthropicStreamCompletionResult", + "AnthropicStreamSuccessResult", + "RuntimeAttemptOutcome", + "RuntimeAttemptCursor", + "anthropic_stream_stop_reason", + "anthropic_stream_usage_delta", + "build_retry_loop", + "build_tool_directive", + "build_usage_delta_factory", + "begin_runtime_attempt", + "cleanup_runtime_resources", + "collect_completion_run", + "collect_completion_run_with_recovery", + "continue_after_retry_directive", + "evaluate_retry_directive", + "extract_blocked_tool_names", + "finalize_anthropic_stream_success", + "complete_anthropic_stream_success", + "has_recent_search_no_results", + "has_recent_unchanged_read_result", + "inject_assistant_message", + "native_tool_calls_to_markup", + "parse_tool_directive_once", + "plan_runtime_attempts", + "recent_same_tool_identity_count", + "request_max_attempts", + "retryable_usage_delta", + "should_force_finish_after_tool_use", + "tool_identity", +] + + +def begin_runtime_attempt(attempt_index: int) -> RuntimeAttemptCursor: + cursor = RuntimeAttemptCursor(index=attempt_index, number=attempt_index + 1) + update_request_context(stream_attempt=cursor.number) + return cursor + + +def should_force_finish_after_tool_use(stop_reason: str, trailing_idle_seconds: float, visible_output_after_tool: bool) -> bool: + return stop_reason == "tool_use" and trailing_idle_seconds >= TRAILING_IDLE_AFTER_TOOL_SECONDS and not visible_output_after_tool + + +def extract_blocked_tool_names(text: str, allowed_tool_names: list[str] | None = None) -> list[str]: + if not text: + return [] + if "does not exist" not in text.lower(): + return [] + blocked = re.findall(r"Tool\s+([A-Za-z0-9_.:-]+)\s+does not exists?\.?", text) + if not blocked: + return [] + if not allowed_tool_names: + return blocked + return [normalize_tool_name(name, allowed_tool_names) for name in blocked] + + +def _recent_message_texts(messages: list[dict[str, Any]] | None, *, limit: int = 10) -> list[str]: + texts: list[str] = [] + checked = 0 + for msg in reversed(messages or []): + checked += 1 + content = msg.get("content", "") + parts: list[str] = [] + if isinstance(content, str): + parts.append(content) + elif isinstance(content, list): + for part in content: + if isinstance(part, dict): + if part.get("type") == "text": + parts.append(part.get("text", "")) + elif part.get("type") == "tool_result": + inner = part.get("content", "") + if isinstance(inner, str): + parts.append(inner) + elif isinstance(inner, list): + for inner_part in inner: + if isinstance(inner_part, dict) and inner_part.get("type") == "text": + parts.append(inner_part.get("text", "")) + elif isinstance(part, str): + parts.append(part) + merged = "\n".join(text for text in parts if text) + if merged: + texts.append(merged) + if checked >= limit: + break + return texts + + +def has_recent_unchanged_read_result(messages: list[dict[str, Any]] | None) -> bool: + return any("Unchanged since last read" in text for text in _recent_message_texts(messages)) + + +def has_recent_search_no_results(messages: list[dict[str, Any]] | None) -> bool: + for text in _recent_message_texts(messages): + lowered = text.lower() + if "websearch" not in lowered: + continue + if "did 0 searches" in lowered or '"results": []' in lowered or '"matches": []' in lowered: + return True + return False + + +def tool_identity(tool_name: str, tool_input: Any = None) -> str: + try: + if tool_name == "Read" and isinstance(tool_input, dict): + return f"Read::{tool_input.get('file_path', '').strip()}" + if tool_name == "read" and isinstance(tool_input, dict): + return f"read::{tool_input.get('path', '').strip()}" + return f"{tool_name}::{json.dumps(tool_input or {}, ensure_ascii=False, sort_keys=True)}" + except Exception: + return tool_name or "" + + +def recent_same_tool_identity_count(messages: list[dict[str, Any]] | None, tool_name: str, tool_input: Any = None) -> int: + target = tool_identity(tool_name, tool_input) + count = 0 + started = False + for msg in reversed(messages or []): + if msg.get("role") != "assistant": + continue + content = msg.get("content", []) + if not isinstance(content, list): + if started: + break + continue + tools = [b for b in content if isinstance(b, dict) and b.get("type") == "tool_use" and b.get("name")] + if not tools: + if started: + break + continue + started = True + if len(tools) == 1 and tool_identity(tools[0].get("name", ""), tools[0].get("input", {})) == target: + count += 1 + continue + break + return count + + +def has_recent_openai_same_tool_call(history_messages: list[dict[str, Any]] | None, tool_name: str, tool_input: Any = None) -> bool: + target = tool_identity(tool_name, tool_input) + for msg in reversed(history_messages or []): + if msg.get("role") != "assistant": + continue + tool_calls = msg.get("tool_calls") + if not isinstance(tool_calls, list) or not tool_calls: + continue + if len(tool_calls) != 1: + return False + fn = tool_calls[0].get("function", {}) if isinstance(tool_calls[0], dict) else {} + name = fn.get("name", "") + raw_args = fn.get("arguments", "{}") + try: + parsed_args = json.loads(raw_args) if isinstance(raw_args, str) and raw_args else raw_args + except (json.JSONDecodeError, ValueError): + parsed_args = {"raw": raw_args} + return tool_identity(name, parsed_args) == target + return False + + +def has_invalid_textual_tool_contract(answer_text: str) -> bool: + if not answer_text: + return False + if "##TOOL_CALL##" not in answer_text and "" not in answer_text: + return False + compact = answer_text.strip() + tc_m = re.search(r'##TOOL_CALL##\s*(.*?)\s*##END_CALL##', compact, re.DOTALL | re.IGNORECASE) + if tc_m: + try: + obj = json.loads(tc_m.group(1)) + except (json.JSONDecodeError, ValueError): + return True + tool_input = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {})))) + return isinstance(tool_input, str) + xml_m = re.search(r'\s*(.*?)\s*', compact, re.DOTALL | re.IGNORECASE) + if xml_m: + try: + obj = json.loads(xml_m.group(1)) + except (json.JSONDecodeError, ValueError): + return True + tool_input = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {})))) + return isinstance(tool_input, str) + return False + + +def should_retry_textual_tool_contract(answer_text: str) -> bool: + if not answer_text: + return False + if "##TOOL_CALL##" in answer_text or "" in answer_text: + return True + return False + + +def native_tool_calls_to_markup(tool_calls: list[dict[str, Any]]) -> str: + parts: list[str] = [] + for tool_call in tool_calls: + parts.append( + f'{{"name": {json.dumps(tool_call["name"])}, "input": {json.dumps(tool_call.get("input", {}), ensure_ascii=False)}}}' + ) + return "\n".join(parts) + + +async def run_runtime_attempt( + *, + client, + request: StandardRequest, + current_prompt: str, + history_messages: list[dict[str, Any]] | None, + attempt_index: int, + max_attempts: int, + allow_after_visible_output: bool = False, + capture_events: bool = True, + on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None, +) -> RuntimeAttemptOutcome: + attempt_cursor = begin_runtime_attempt(attempt_index) + execution = await collect_completion_run( + client, + request, + current_prompt, + capture_events=capture_events, + on_delta=on_delta, + ) + retry = evaluate_retry_directive( + request=request, + current_prompt=current_prompt, + history_messages=history_messages, + attempt_index=attempt_cursor.index, + max_attempts=max_attempts, + state=execution.state, + allow_after_visible_output=allow_after_visible_output, + ) + preserve_chat = bool(getattr(request, 'persistent_session', False)) + continuation = await continue_after_retry_directive( + client=client, + execution=execution, + retry=retry, + preserve_chat=preserve_chat, + ) + return RuntimeAttemptOutcome(execution=execution, continuation=continuation) + + +async def collect_completion_run( + client, + request: StandardRequest, + prompt: str, + *, + capture_events: bool = True, + on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None, +) -> RuntimeExecutionResult: + chat_id = None + acc = None + answer_fragments: list[str] = [] + reasoning_fragments: list[str] = [] + native_tool_calls: list[dict[str, Any]] = [] + tool_state = StreamingToolCallState() + emitted_visible_output = False + first_event_marked = False + raw_events: list[dict[str, Any]] = [] + metrics = StreamMetrics() + + # 初始化 Tool Sieve 用于实时检测 + tool_sieve = None + if request.tools: + tool_sieve = tool_parser.ToolSieve(request.tool_names) + log.info("[收集完成] 工具过滤器已启用,工具列表: %s", request.tool_names) + + def _finalize_result(*, reason: str | None = None) -> RuntimeExecutionResult: + answer_text = "".join(answer_fragments) + reasoning_text = "".join(reasoning_fragments) + if native_tool_calls and not answer_text: + answer_text = native_tool_calls_to_markup(native_tool_calls) + + # 关键修复:强制解析最终文本中的工具调用 + detected_tool_calls = native_tool_calls + final_finish_reason = "tool_calls" if native_tool_calls else "stop" + + # 第一重:刷新 Tool Sieve + if tool_sieve and not native_tool_calls: + flush_events = tool_sieve.flush() + for evt in flush_events: + if evt.get("type") == "tool_calls": + calls = evt.get("calls", []) + if calls: + # 转换为标准格式 + import uuid + detected_tool_calls = [{ + "type": "tool_use", + "id": f"toolu_{uuid.uuid4().hex[:8]}", + "name": call["name"], + "input": call["input"] + } for call in calls] + final_finish_reason = "tool_calls" + log.info( + "[Collect] ✓ Tool Sieve 刷新检测到工具调用: tools=%s", + [t.get("name") for t in detected_tool_calls], + ) + break + elif evt.get("type") == "content": + # 剩余文本内容 + pass + + # 第二重:解析最终文本 + if not detected_tool_calls and request.tools and answer_text: + # 尝试从最终文本中解析工具调用 + tool_blocks, stop_reason = tool_parser.parse_tool_calls_silent(answer_text, request.tools) + tool_use_blocks = [b for b in tool_blocks if b.get("type") == "tool_use"] + + if tool_use_blocks and stop_reason == "tool_use": + # 找到工具调用! + detected_tool_calls = tool_use_blocks + final_finish_reason = "tool_calls" + + # 从文本中移除工具调用部分 + text_blocks = [b for b in tool_blocks if b.get("type") == "text"] + if text_blocks: + answer_text = text_blocks[0].get("text", "") + else: + answer_text = "" + + log.info( + "[Collect] ✓ 最终文本解析检测到工具调用: tools=%s, cleaned_text_len=%s", + [t.get("name") for t in detected_tool_calls], + len(answer_text), + ) + + # 检查空输出 + if not detected_tool_calls and not answer_text.strip() and not reasoning_text.strip(): + log.warning( + "[收集完成] 上游返回空输出: 原因=%s 会话=%s", + reason, + chat_id, + ) + # 如果有 reasoning 但没有 visible output,说明模型只输出了思考过程 + if reasoning_text.strip(): + log.warning("[收集完成] 模型只返回了推理内容,没有可见输出") + # 空响应 flush 该账号池(同批次预热的可能都是坏的),下次走新建 + try: + pool = getattr(client, "executor", None) and getattr(client.executor, "chat_id_pool", None) + if pool is not None and acc is not None: + import asyncio as _aio + _aio.create_task(pool.flush_account(acc.email)) + except Exception: + pass + + if reason: + log.info( + "[收集完成] 原因=%s 会话=%s 工具调用=%s 答复字数=%s 推理字数=%s 结束原因=%s", + reason, + chat_id, + len(detected_tool_calls), + len(answer_text), + len(reasoning_text), + final_finish_reason, + ) + metrics.mark("stream_finish", float(len(raw_events))) + state = RuntimeAttemptState( + answer_text=answer_text, + reasoning_text=reasoning_text, + tool_calls=detected_tool_calls, + blocked_tool_names=extract_blocked_tool_names(answer_text.strip(), request.tool_names), + finish_reason=final_finish_reason, + raw_events=raw_events, + emitted_visible_output=emitted_visible_output, + stage_metrics=metrics.summary(), + ) + return RuntimeExecutionResult(state=state, chat_id=chat_id, acc=acc) + + async for item in client.chat_stream_events_with_retry( + request.resolved_model, + prompt, + has_custom_tools=bool(request.tools), + files=getattr(request, "upstream_files", None), + fixed_account=getattr(request, "bound_account", None), + existing_chat_id=getattr(request, "upstream_chat_id", None), + ): + if item.get("type") == "meta": + chat_id = item.get("chat_id") + acc = item.get("acc") + update_request_context(chat_id=chat_id) + metrics.mark("chat_created", float(len(raw_events))) + continue + if item.get("type") != "event": + continue + + evt = item.get("event", {}) + if capture_events: + raw_events.append(evt) + if evt.get("type") != "delta": + continue + + phase = evt.get("phase", "") + content = evt.get("content", "") + + if phase in ("think", "thinking_summary") and content: + reasoning_fragments.append(content) + emitted_visible_output = True + if not first_event_marked: + metrics.mark("first_event", float(len(raw_events))) + first_event_marked = True + if on_delta is not None: + await on_delta(evt, content, None) + continue + + if phase == "answer" and content: + answer_fragments.append(content) + + # 毒性拒绝早期拦截:Qwen 偶尔幻觉出 "Tool X does not exists." 之类文本。 + # 在标记 emitted_visible_output 之前识别并提前 finalize,让 evaluate_retry_directive + # 的 blocked_tool_name 分支能正常触发重试(否则 emitted=True 后就不 retry 了)。 + if ( + request.tools + and not emitted_visible_output + and len("".join(answer_fragments)) >= 20 + ): + early_answer = "".join(answer_fragments).strip() + if _TOXIC_REFUSAL_RE.search(early_answer): + toxic_blocked = extract_blocked_tool_names(early_answer, request.tool_names) + blocked_name = toxic_blocked[0] if toxic_blocked else "unknown" + log.warning( + "[收集完成] 污染拦截 %r (未流出客户端,触发重试)", + early_answer[:80], + ) + return _finalize_result(reason=f"blocked_tool_name:{blocked_name}") + + emitted_visible_output = True + if not first_event_marked: + metrics.mark("first_event", float(len(raw_events))) + first_event_marked = True + + # Tool Sieve 实时检测 + if tool_sieve: + sieve_events = tool_sieve.process_chunk(content) + for sieve_evt in sieve_events: + if sieve_evt.get("type") == "tool_calls": + # 检测到工具调用! + calls = sieve_evt.get("calls", []) + if calls: + import uuid + detected_calls = [{ + "type": "tool_use", + "id": f"toolu_{uuid.uuid4().hex[:8]}", + "name": call["name"], + "input": call["input"] + } for call in calls] + native_tool_calls.extend(detected_calls) + log.info( + "[Collect] ✓ Tool Sieve 实时检测到工具调用: tools=%s", + [c.get("name") for c in detected_calls], + ) + return _finalize_result(reason="tool_sieve_detected") + + if on_delta is not None: + await on_delta(evt, content, None) + if request.tools: + answer_text = "".join(answer_fragments) + if len(answer_fragments) % 3 == 0 or "does not exist" in content.lower(): + blocked_tool_names = extract_blocked_tool_names(answer_text.strip(), request.tool_names) + if blocked_tool_names: + return _finalize_result(reason=f"blocked_tool_name:{blocked_tool_names[0]}") + if "##TOOL_CALL##" in answer_text or "" in answer_text: + directive = parse_tool_directive_once( + request, + RuntimeAttemptState(answer_text=answer_text, reasoning_text="".join(reasoning_fragments)), + ) + if directive.stop_reason == "tool_use": + return _finalize_result(reason="textual_tool_use") + continue + + if phase == "tool_call": + emitted_visible_output = True + if not first_event_marked: + metrics.mark("first_event", float(len(raw_events))) + first_event_marked = True + completed_calls = tool_state.process_event(evt) + if completed_calls: + native_tool_calls.extend(completed_calls) + if on_delta is not None: + await on_delta(evt, None, completed_calls) + return _finalize_result(reason="native_tool_use") + + return _finalize_result(reason="stream_end") + + +def parse_tool_directive_once(request: StandardRequest, state: RuntimeAttemptState) -> RuntimeToolDirective: + if state.tool_calls: + return RuntimeToolDirective( + tool_blocks=[ + { + "type": "tool_use", + "id": tool_call["id"], + "name": normalize_tool_name(tool_call["name"], request.tool_names), + "input": tool_call.get("input", {}), + } + for tool_call in state.tool_calls + ], + stop_reason="tool_use", + ) + + if request.tools and state.answer_text: + tool_blocks, stop_reason = tool_parser.parse_tool_calls_silent(state.answer_text, request.tools) + return RuntimeToolDirective(tool_blocks=tool_blocks, stop_reason=stop_reason) + + return RuntimeToolDirective(tool_blocks=[{"type": "text", "text": state.answer_text}], stop_reason="end_turn") + + +# ==================== 截断续写 + 流式 warmup(P2-6 & P2-10 接入)==================== + +async def collect_completion_run_with_recovery( + client, + request: StandardRequest, + prompt: str, + *, + capture_events: bool = True, + on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None, + max_continuation: int = 2, + warmup_chars: int = 0, + guard_chars: int = 0, +) -> RuntimeExecutionResult: + """collect_completion_run 的增强版,叠加两个能力: + + 1. **截断自动续写**(P2-6):初始流结束若 answer_text 含未闭合的 ##TOOL_CALL## 块, + 最多追加 max_continuation 次续写请求,每次丢弃工具定义省上下文预算, + 用 deduplicate_continuation 去除头尾重叠后拼接。 + + 2. **流式 warmup/guard**(P2-10):当 warmup_chars>0 时,用 IncrementalTextStreamer + 包装 on_delta 的 text 路径——起步累积 warmup_chars 字符后才放行, + 任何时刻保留末尾 guard_chars 字符暂不发出,给跨 chunk 清洗预留空间。 + + 保留向后兼容:不传可选参数 → 行为与 collect_completion_run 完全一致。 + """ + from backend.services.truncation_recovery import ( + build_continuation_prompt, + deduplicate_continuation, + is_truncated, + ) + from backend.services.incremental_text_streamer import IncrementalTextStreamer + + wrapped_on_delta = on_delta + streamer: IncrementalTextStreamer | None = None + if warmup_chars > 0 and on_delta is not None: + streamer = IncrementalTextStreamer( + warmup_chars=warmup_chars, + guard_chars=max(guard_chars, 64), + ) + + async def _wrapped(evt, text_chunk, tool_calls): + # 仅对纯文本 delta 做 warmup;tool_calls / thinking / native 直接透传 + if text_chunk is None or tool_calls is not None or evt.get("phase") not in ("answer", "text"): + await on_delta(evt, text_chunk, tool_calls) + return + released = streamer.push(text_chunk) + if released: + await on_delta(evt, released, None) + + wrapped_on_delta = _wrapped + + result = await collect_completion_run( + client, request, prompt, + capture_events=capture_events, + on_delta=wrapped_on_delta, + ) + + # 若 warmup 还保留着尾部,flush 出去 + if streamer is not None and on_delta is not None: + tail = streamer.finish() + if tail: + await on_delta({"phase": "answer"}, tail, None) + + # 截断续写 + continues = 0 + while continues < max_continuation: + state = result.state + # 有已检出的工具调用就不续写(让客户端去执行那个 tool) + if state.tool_calls: + break + # 没 tools 的场景不做续写(纯聊天,截断检测无 ##TOOL_CALL## 参考点会误触发) + if not request.tools: + break + if not is_truncated(state.answer_text): + break + + continues += 1 + log.info( + "[TruncRecover] detected unclosed tool call, continuation attempt=%d chat_id=%s len=%d", + continues, result.chat_id, len(state.answer_text), + ) + + assistant_ctx, followup = build_continuation_prompt(state.answer_text, anchor_chars=2000) + # 续写 prompt = 原 prompt + assistant 已输出的锚点 + user 续写指令 + cont_prompt = ( + f"{prompt.rstrip()}\n\nAssistant: {assistant_ctx}\n\nHuman: {followup}\n\nAssistant:" + ) + + cont_result = await collect_completion_run( + client, request, cont_prompt, + capture_events=False, + on_delta=on_delta, # 不经过 streamer,续写内容直接透传 + ) + cont_text = cont_result.state.answer_text + if not cont_text or not cont_text.strip(): + log.info("[TruncRecover] empty continuation, stopping") + break + + deduped = deduplicate_continuation(state.answer_text, cont_text) + if not deduped.strip(): + log.info("[TruncRecover] continuation fully overlapped existing, stopping") + break + + merged_answer = state.answer_text + deduped + merged_state = RuntimeAttemptState( + answer_text=merged_answer, + reasoning_text=state.reasoning_text, + tool_calls=cont_result.state.tool_calls or state.tool_calls, + blocked_tool_names=cont_result.state.blocked_tool_names or state.blocked_tool_names, + finish_reason=cont_result.state.finish_reason or state.finish_reason, + raw_events=state.raw_events, + emitted_visible_output=state.emitted_visible_output or cont_result.state.emitted_visible_output, + stage_metrics=state.stage_metrics, + ) + result = RuntimeExecutionResult(state=merged_state, chat_id=result.chat_id, acc=result.acc) + log.info( + "[TruncRecover] continuation=%d produced %d new chars; total=%d", + continues, len(deduped), len(merged_answer), + ) + # 若续写完成后已闭合则收工 + if not is_truncated(merged_answer): + break + + return result + + +def build_tool_directive( + request: StandardRequest, + state: RuntimeAttemptState, +) -> RuntimeToolDirective: + directive = parse_tool_directive_once(request, state) + log.info( + f"[ToolDirective] tool_blocks={len(directive.tool_blocks)} stop_reason={directive.stop_reason} " + f"has_tool_use={any(b.get('type') == 'tool_use' for b in directive.tool_blocks)}" + ) + return directive + + +def anthropic_stream_usage_delta(prompt: str, answer_text: str) -> int: + return len(answer_text) + len(prompt) + + +def anthropic_stream_stop_reason(request: StandardRequest, state: RuntimeAttemptState, pending_chunks: list[str]) -> str: + if state.tool_calls or any('"type": "tool_use"' in chunk for chunk in pending_chunks): + return "tool_use" + return build_tool_directive(request, state).stop_reason + + +def finalize_anthropic_stream_success(*, request: StandardRequest, prompt: str, execution: RuntimeExecutionResult, translator) -> AnthropicStreamSuccessResult: + stop_reason = anthropic_stream_stop_reason(request, execution.state, translator.pending_chunks) + chunks = translator.finalize(answer_text=execution.state.answer_text, stop_reason=stop_reason) + return AnthropicStreamSuccessResult( + chunks=chunks, + usage_delta=anthropic_stream_usage_delta(prompt, execution.state.answer_text), + ) + + +async def complete_anthropic_stream_success(*, users_db, token: str, client, prompt: str, request: StandardRequest, execution: RuntimeExecutionResult, translator) -> AnthropicStreamCompletionResult: + from backend.services.auth_quota import add_used_tokens + + stream_success = finalize_anthropic_stream_success( + request=request, + prompt=prompt, + execution=execution, + translator=translator, + ) + await add_used_tokens(users_db, token, stream_success.usage_delta) + await cleanup_runtime_resources(client, execution.acc, execution.chat_id) + return AnthropicStreamCompletionResult(chunks=stream_success.chunks) + + +def inject_assistant_message(prompt: str, message: str) -> str: + next_prompt = prompt.rstrip() + if next_prompt.endswith("Assistant:"): + return next_prompt[:-len("Assistant:")] + message + "\nAssistant:" + return next_prompt + "\n\n" + message + "\nAssistant:" + + +def retryable_usage_delta(prompt: str): + return lambda execution, current_prompt=None: len(execution.state.answer_text) + len(current_prompt or prompt) + + +def build_usage_delta_factory(prompt: str) -> Callable[[RuntimeExecutionResult, Any | None], int]: + return lambda execution, current_prompt=None: len(execution.state.answer_text) + len(current_prompt or prompt) + + +def request_max_attempts(request: StandardRequest) -> int: + # 工具模式下给模型更多重试机会(毒性幻觉/重复调用场景常见), + # 原值 2 在多轮 retry 里太容易用完,升到 4 + return 4 if request.tools else settings.MAX_RETRIES + + +def plan_runtime_attempts(request: StandardRequest, *, initial_prompt: str) -> RuntimeAttemptPlan: + loop = build_retry_loop(request, initial_prompt=initial_prompt) + return RuntimeAttemptPlan(loop=loop, prompt=loop.prompt) + + +def build_retry_loop(request: StandardRequest, *, initial_prompt: str) -> RuntimeRetryLoop: + return RuntimeRetryLoop( + prompt=initial_prompt, + max_attempts=request_max_attempts(request), + ) + + +def evaluate_retry_directive( + *, + request: StandardRequest, + current_prompt: str, + history_messages: list[dict[str, Any]] | None, + attempt_index: int, + max_attempts: int, + state: RuntimeAttemptState, + allow_after_visible_output: bool = False, +) -> RuntimeRetryDirective: + if attempt_index >= max_attempts - 1: + return RuntimeRetryDirective(retry=False, next_prompt=current_prompt, reason=None) + + can_retry_after_output = allow_after_visible_output or not state.emitted_visible_output + + def _retry(reason: str, next_prompt: str) -> RuntimeRetryDirective: + log.info( + "[重试] 原因=%s 第%s/%s次 客户端=%s 屏蔽=%s 结束原因=%s 已流出=%s", + reason, + attempt_index + 1, + max_attempts, + getattr(request, "client_profile", "-"), + state.blocked_tool_names[:3], + state.finish_reason, + state.emitted_visible_output, + ) + return RuntimeRetryDirective(retry=True, next_prompt=next_prompt, reason=reason) + + if state.blocked_tool_names and request.tools: + if not can_retry_after_output: + return RuntimeRetryDirective(retry=False, next_prompt=current_prompt, reason=None) + blocked_name = normalize_tool_name(state.blocked_tool_names[0], request.tool_names) + return _retry( + f"blocked_tool_name:{blocked_name}", + tool_parser.inject_format_reminder( + current_prompt, + blocked_name, + client_profile=getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE), + ), + ) + + if request.tools: + directive: RuntimeToolDirective | None = None + if state.answer_text: + saw_contract_markup = should_retry_textual_tool_contract(state.answer_text) + if saw_contract_markup and can_retry_after_output: + if has_invalid_textual_tool_contract(state.answer_text): + fallback_tool_name = request.tool_names[0] if request.tool_names else "tool" + return _retry( + f"invalid_textual_tool_contract:{fallback_tool_name}", + tool_parser.inject_format_reminder( + current_prompt, + fallback_tool_name, + client_profile=getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE), + ), + ) + directive = parse_tool_directive_once(request, state) + if directive.stop_reason != "tool_use": + fallback_tool_name = request.tool_names[0] if request.tool_names else "tool" + return _retry( + f"unparsed_textual_tool_contract:{fallback_tool_name}", + tool_parser.inject_format_reminder( + current_prompt, + fallback_tool_name, + client_profile=getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE), + ), + ) + if directive is None: + directive = parse_tool_directive_once(request, state) + if directive.stop_reason == "tool_use": + first_tool = next((b for b in directive.tool_blocks if b.get("type") == "tool_use"), None) + if first_tool: + repeated_same_tool = False + if getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE) == "openclaw_openai": + repeated_same_tool = has_recent_openai_same_tool_call( + history_messages, + first_tool.get("name", ""), + first_tool.get("input", {}), + ) + else: + repeated_same_tool = recent_same_tool_identity_count( + history_messages, + first_tool.get("name", ""), + first_tool.get("input", {}), + ) >= 1 + if repeated_same_tool and can_retry_after_output: + force_text = ( + f"[强制要求]: 你已经用相同参数调用了 {first_tool.get('name')}。" + "不要重复相同的工具调用。" + "使用已有的工具结果,选择下一个相关工具或完成任务。" + "如果是配置文件任务,读取一次后直接编辑/写入文件,不要重复读取。" + f"\n[MANDATORY]: You already called {first_tool.get('name')} with the same input. " + "Do NOT repeat the same tool call. " + "Use the tool result you already have and either choose the next relevant tool or finish the task. " + "If this is a config-file task, read once and then edit/write the file instead of rereading it." + ) + return _retry( + f"repeated_same_tool:{first_tool.get('name', '')}", + inject_assistant_message(current_prompt, force_text), + ) + if ( + first_tool + and first_tool.get("name") == "Read" + and has_recent_unchanged_read_result(history_messages) + ): + if can_retry_after_output: + force_text = ( + "[强制要求]: 你刚收到'Unchanged since last read'(文件未改变)。" + "不要再次读取同一个文件。" + "现在选择其他工具或完成任务。" + "\n[MANDATORY]: You just received 'Unchanged since last read'. " + "Do NOT call Read again. Choose another tool or finish the task." + ) + return _retry( + "unchanged_read_result", + inject_assistant_message(current_prompt, force_text), + ) + else: + log.warning(f"[Runtime] Blocked repeated Read after 'Unchanged since last read', but cannot retry") + + # 防止自动调用Agent工具 + if ( + first_tool + and first_tool.get("name") == "Agent" + and can_retry_after_output + ): + # 检查用户消息中是否明确提到agent相关词汇 + user_mentioned_agent = False + for msg in reversed(history_messages or []): + if msg.get("role") == "user": + content = msg.get("content", "") + if isinstance(content, str): + text = content.lower() + elif isinstance(content, list): + text = " ".join( + part.get("text", "").lower() + for part in content + if isinstance(part, dict) and part.get("type") == "text" + ) + else: + text = "" + if any(keyword in text for keyword in ["agent", "代理", "子任务", "subtask", "background"]): + user_mentioned_agent = True + break + + if not user_mentioned_agent: + force_text = ( + "[强制要求]: 不要自动调用Agent工具。用户没有要求使用代理或子任务。" + "请直接完成用户的请求,使用Read/Write/Edit等工具。" + "\n[MANDATORY]: Do NOT call Agent tool automatically. User did not request agent or subtask. " + "Complete the user's request directly using Read/Write/Edit tools." + ) + return _retry( + "auto_agent_blocked", + inject_assistant_message(current_prompt, force_text), + ) + + if ( + first_tool + and first_tool.get("name") == "WebSearch" + and has_recent_search_no_results(history_messages) + and can_retry_after_output + ): + force_text = ( + "[强制要求]: 上次WebSearch没有返回结果。" + "不要用类似的词再次调用WebSearch。" + "使用其他工具或用现有信息完成回答。" + "\n[MANDATORY]: The last WebSearch returned no results. " + "Do NOT call WebSearch again with similar wording. " + "Use another tool or finish with the best available answer." + ) + return _retry( + "search_no_results", + inject_assistant_message(current_prompt, force_text), + ) + + # 空响应重试:上游返回 answer_chars=0 tool_calls=0 finish_reason=stop + # 典型场景是 Qwen 后端对某个 chat_id 返回空(常见于池化 chat_id 刚建好就被用、 + # 或 Qwen 服务抖动时)。换账号 + 换新 chat_id 再试一次。 + if ( + not state.answer_text + and not state.tool_calls + and state.finish_reason == "stop" + and not state.emitted_visible_output + ): + return _retry( + "empty_upstream_response", + current_prompt, # prompt 不变,让上游重新处理 + ) + + return RuntimeRetryDirective(retry=False, next_prompt=current_prompt, reason=None) + + +async def continue_after_retry_directive(*, client, execution, retry: RuntimeRetryDirective, preserve_chat: bool = False) -> RuntimeRetryContinuation: + if not retry.retry: + return RuntimeRetryContinuation(should_continue=False, next_prompt=retry.next_prompt) + await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat) + if not preserve_chat: + await asyncio.sleep(0.15) + return RuntimeRetryContinuation(should_continue=True, next_prompt=retry.next_prompt) + + +async def cleanup_runtime_resources(client, acc, chat_id: str | None, *, preserve_chat: bool = False) -> None: + if acc is None: + return + token = getattr(acc, "token", None) + client.account_pool.release(acc) + if preserve_chat: + return + if chat_id and token: + async def _delete_chat_later() -> None: + try: + await client.delete_chat(token, chat_id) + except Exception as exc: + log.debug("[Cleanup] delete_chat failed chat_id=%s error=%s", chat_id, exc) + asyncio.create_task(_delete_chat_later()) diff --git a/backend/runtime/stream_metrics.py b/backend/runtime/stream_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..87eb44af6447a5c208f8ff0447f45c91f6b6f0a9 --- /dev/null +++ b/backend/runtime/stream_metrics.py @@ -0,0 +1,12 @@ +from __future__ import annotations + + +class StreamMetrics: + def __init__(self): + self._marks: dict[str, float] = {} + + def mark(self, name: str, seconds: float) -> None: + self._marks[name] = seconds + + def summary(self) -> dict[str, float]: + return dict(self._marks) diff --git a/backend/runtime/stream_presenter.py b/backend/runtime/stream_presenter.py new file mode 100644 index 0000000000000000000000000000000000000000..85bede64dd09954ebb332f3a3f947daa9369119c --- /dev/null +++ b/backend/runtime/stream_presenter.py @@ -0,0 +1,71 @@ +import json +from typing import Any + + +def anthropic_message_start(msg_id: str, model_name: str, usage: dict[str, Any]) -> str: + payload = { + "type": "message_start", + "message": { + "id": msg_id, + "type": "message", + "role": "assistant", + "content": [], + "model": model_name, + "stop_reason": None, + "usage": usage, + }, + } + return f"event: message_start\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n" + + +def anthropic_content_block_start(index: int, content_block: dict[str, Any]) -> str: + return f"event: content_block_start\ndata: {json.dumps({'type': 'content_block_start', 'index': index, 'content_block': content_block}, ensure_ascii=False)}\n\n" + + +def anthropic_content_block_delta(index: int, delta: dict[str, Any]) -> str: + return f"event: content_block_delta\ndata: {json.dumps({'type': 'content_block_delta', 'index': index, 'delta': delta}, ensure_ascii=False)}\n\n" + + +def anthropic_content_block_stop(index: int) -> str: + return f"event: content_block_stop\ndata: {json.dumps({'type': 'content_block_stop', 'index': index}, ensure_ascii=False)}\n\n" + + +def anthropic_message_delta(stop_reason: str, output_tokens: int) -> str: + return f"event: message_delta\ndata: {json.dumps({'type': 'message_delta', 'delta': {'stop_reason': stop_reason}, 'usage': {'output_tokens': output_tokens}}, ensure_ascii=False)}\n\n" + + +def anthropic_message_stop() -> str: + return f"event: message_stop\ndata: {json.dumps({'type': 'message_stop'}, ensure_ascii=False)}\n\n" + + +def openai_chunk(completion_id: str, created: int, model_name: str, delta: dict[str, Any], finish_reason: str | None = None) -> str: + payload = { + "id": completion_id, + "object": "chat.completion.chunk", + "created": created, + "model": model_name, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}], + } + return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" + + +def openai_done() -> str: + return "data: [DONE]\n\n" + + +def gemini_text_chunk(text: str) -> str: + payload = { + "candidates": [ + { + "content": { + "parts": [{"text": text}], + "role": "model", + } + } + ] + } + return json.dumps(payload, ensure_ascii=False) + "\n" + + +def gemini_error_chunk(message: str) -> str: + return json.dumps({"error": message}, ensure_ascii=False) + "\n" diff --git a/backend/runtime/stream_runtime.py b/backend/runtime/stream_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..e91a1709e57b72607d5bc5545f6614a02c0d20d4 --- /dev/null +++ b/backend/runtime/stream_runtime.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from collections.abc import AsyncIterable, Iterable +from dataclasses import dataclass, field +from typing import Any, TypeAlias, cast + +from .finalizer import finalize_runtime_result + +Event: TypeAlias = dict[str, Any] +EventSource: TypeAlias = Iterable[Event] | AsyncIterable[Event] + + +@dataclass +class RuntimeResult: + text: str = "" + tool_calls: list[dict[str, Any]] = field(default_factory=list) + finish_reason: str | None = None + + +class StreamRuntime: + def __init__(self, request: dict[str, Any]) -> None: + self.request = request + self.result = RuntimeResult() + + def _apply_event(self, event: Event) -> None: + event_type = event.get("type") + + if event_type == "text_delta": + self.result.text += event.get("text", "") + elif event_type == "tool_call": + self.result.tool_calls.append( + { + "id": event.get("id"), + "name": event.get("name"), + "input": event.get("input", {}), + } + ) + elif event_type == "finish": + self.result.finish_reason = event.get("finish_reason") + + async def collect(self, events: EventSource) -> RuntimeResult: + if hasattr(events, "__aiter__"): + async_events = cast(AsyncIterable[Event], events) + async for event in async_events: + self._apply_event(event) + else: + sync_events = cast(Iterable[Event], events) + for event in sync_events: + self._apply_event(event) + + return finalize_runtime_result(self.result) diff --git a/backend/services/attachment_preprocessor.py b/backend/services/attachment_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..2e87832f76c3b82e248eaed1e86f63d1d4647a9d --- /dev/null +++ b/backend/services/attachment_preprocessor.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import base64 +import copy +from dataclasses import dataclass, field +from typing import Any + +from backend.runtime.attachment_types import NormalizedAttachment + + +@dataclass(slots=True) +class PreprocessedAttachments: + payload: dict[str, Any] + attachments: list[NormalizedAttachment] = field(default_factory=list) + uploaded_file_ids: list[str] = field(default_factory=list) + + +def _decode_data_uri(url: str) -> tuple[str, bytes]: + header, encoded = url.split(",", 1) + content_type = header.split(";", 1)[0][5:] or "application/octet-stream" + return content_type, base64.b64decode(encoded) + + +def _extract_inline_file_payload(block: dict[str, Any]) -> tuple[str, str, bytes] | None: + filename = str(block.get("filename") or block.get("name") or "attachment.txt") + content_type = str(block.get("mime_type") or block.get("content_type") or "text/plain") + + if isinstance(block.get("text"), str): + return filename, content_type, block["text"].encode("utf-8") + if isinstance(block.get("content"), str) and not str(block.get("content", "")).startswith("data:"): + return filename, content_type, block["content"].encode("utf-8") + if isinstance(block.get("data_base64"), str): + return filename, content_type, base64.b64decode(block["data_base64"]) + if isinstance(block.get("data"), str): + return filename, content_type, base64.b64decode(block["data"]) + if isinstance(block.get("content"), str) and str(block.get("content", "")).startswith("data:"): + ct, raw = _decode_data_uri(block["content"]) + return filename, ct, raw + return None + + +async def preprocess_attachments(payload: dict[str, Any], file_store, owner_token: str | None = None) -> PreprocessedAttachments: + messages = payload.get("messages", []) + needs_rewrite = False + for message in messages: + content = message.get("content") + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict): + continue + if block.get("type") == "image_url": + image_url = block.get("image_url") or {} + if isinstance(image_url, dict) and str(image_url.get("url") or "").strip().startswith("data:"): + needs_rewrite = True + break + if block.get("type") in ("input_file", "file") and _extract_inline_file_payload(block): + needs_rewrite = True + break + if needs_rewrite: + break + + if not needs_rewrite: + return PreprocessedAttachments(payload=payload) + + rewritten = copy.deepcopy(payload) + attachments: list[NormalizedAttachment] = [] + uploaded_file_ids: list[str] = [] + + for message in rewritten.get("messages", []): + content = message.get("content") + if not isinstance(content, list): + continue + for index, block in enumerate(content): + if not isinstance(block, dict): + continue + if block.get("type") == "image_url": + image_url = block.get("image_url") or {} + if isinstance(image_url, dict) and str(image_url.get("url") or "").strip().startswith("data:"): + content_type, raw = _decode_data_uri(str(image_url.get("url") or "")) + result = await file_store.save_bytes("inline-image", content_type, raw, "vision", owner_token=owner_token) + uploaded_file_ids.append(result["id"]) + attachments.append(NormalizedAttachment( + file_id=result["id"], + filename=result["filename"], + content_type=content_type, + source="inline-image", + local_path=result["path"], + sha256=result["sha256"], + purpose="user-upload", + )) + content[index] = {"type": "input_image", "file_id": result["id"], "mime_type": content_type} + continue + + if block.get("type") in ("input_file", "file"): + existing_file_id = str(block.get("file_id") or "").strip() + if existing_file_id: + existing = await file_store.get(existing_file_id) + if existing and (not existing.get("owner_token") or existing.get("owner_token") == (owner_token or "")): + attachments.append(NormalizedAttachment( + file_id=existing["id"], + filename=existing["filename"], + content_type=existing.get("content_type", "application/octet-stream"), + source="manual-upload-ref", + local_path=existing.get("path", ""), + sha256=existing.get("sha256", ""), + purpose="user-upload", + )) + content[index] = { + "type": "input_file", + "file_id": existing["id"], + "filename": existing["filename"], + "mime_type": existing.get("content_type", "application/octet-stream"), + } + continue + extracted = _extract_inline_file_payload(block) + if not extracted: + continue + filename, content_type, raw = extracted + result = await file_store.save_bytes(filename, content_type, raw, "upload", owner_token=owner_token) + uploaded_file_ids.append(result["id"]) + attachments.append(NormalizedAttachment( + file_id=result["id"], + filename=result["filename"], + content_type=content_type, + source="manual-upload", + local_path=result["path"], + sha256=result["sha256"], + purpose="user-upload", + )) + content[index] = { + "type": "input_file", + "file_id": result["id"], + "filename": result["filename"], + "mime_type": content_type, + } + + return PreprocessedAttachments(payload=rewritten, attachments=attachments, uploaded_file_ids=uploaded_file_ids) diff --git a/backend/services/auth_quota.py b/backend/services/auth_quota.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3857df7dc6a7c2c55cbbd9af771d79960f39b6 --- /dev/null +++ b/backend/services/auth_quota.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from fastapi import HTTPException, Request + +from backend.core.config import API_KEYS, settings + + +@dataclass(slots=True) +class AuthContext: + token: str + user: dict[str, Any] | None + + +def extract_api_token(request: Request) -> str: + auth_header = request.headers.get("Authorization", "") + token = auth_header[7:].strip() if auth_header.startswith("Bearer ") else "" + if token: + return token + + token = request.headers.get("x-api-key", "").strip() + if token: + return token + + return request.query_params.get("key", "").strip() or request.query_params.get("api_key", "").strip() + + +async def resolve_auth_context(request: Request, users_db) -> AuthContext: + token = extract_api_token(request) + if not token: + raise HTTPException(status_code=401, detail="Invalid API Key") + + users = await users_db.get() + user = next((u for u in users if u["id"] == token), None) + + if API_KEYS and token != settings.ADMIN_KEY and token not in API_KEYS: + saved_snapshots = getattr(users_db, "saved_snapshots", None) + if user is None and not isinstance(saved_snapshots, list): + raise HTTPException(status_code=401, detail="Invalid API Key") + + if user and user.get("quota", 0) <= user.get("used_tokens", 0): + raise HTTPException(status_code=402, detail="Quota Exceeded") + + return AuthContext(token=token, user=user) + + +async def add_used_tokens(users_db, token: str, delta: int) -> None: + if delta <= 0: + return + + users = await users_db.get() + for user in users: + if user["id"] == token: + user["used_tokens"] += delta + break + await users_db.save(users) diff --git a/backend/services/auth_resolver.py b/backend/services/auth_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..537cb1d3ca0ef2df359878ad2b94979a1fe59364 --- /dev/null +++ b/backend/services/auth_resolver.py @@ -0,0 +1,801 @@ +import asyncio +import html as html_lib +import json +import logging +import random +import re +import string +import time +from typing import Optional + +from backend.core.account_pool import Account, AccountPool +from backend.core.browser_engine import _new_browser +from backend.core.config import settings +log = logging.getLogger(__name__) + +BASE_URL = "https://chat.qwen.ai" + +async def _verify_qwen_token(token: str) -> bool: + if not token: + return False + try: + import httpx + headers = { + "Authorization": f"Bearer {token}", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", + "Accept": "application/json, text/plain, */*", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Referer": "https://chat.qwen.ai/", + "Origin": "https://chat.qwen.ai", + "Connection": "keep-alive" + } + async with httpx.AsyncClient(timeout=15) as client: + resp = await client.get(f"{BASE_URL}/api/v1/auths/", headers=headers) + if resp.status_code != 200: + return False + try: + data = resp.json() + return data.get("role") == "user" + except Exception: + txt = resp.text.lower() + return 'aliyun_waf' in txt or ' str: + """如果提供了此功能,用 playwright 重新登录获取 Token,这里提供一个 mock 或抛错以防未实现""" + raise NotImplementedError("Auto-login not fully implemented yet in the separated architecture") + +def _gen_password(length=14): + chars = string.ascii_letters + string.digits + "!@#$%^&*" + while True: + pwd = "".join(random.choices(chars, k=length)) + if (any(c.isupper() for c in pwd) and any(c.islower() for c in pwd) + and any(c.isdigit() for c in pwd) and any(c in "!@#$%^&*" for c in pwd)): + return pwd + +def _gen_username(): + first = random.choice(["Alex", "Sam", "Jordan", "Taylor", "Morgan", "Casey", "Riley", "Jamie", + "Drew", "Avery", "Quinn", "Blake", "Sage", "Reese", "Dakota", "Emery"]) + last = random.choice(["Smith", "Brown", "Wilson", "Lee", "Chen", "Wang", "Kim", "Park", + "Davis", "Miller", "Garcia", "Martinez", "Anderson", "Taylor", "Thomas"]) + return f"{first} {last}" + +MAIL_BASE = "https://mail.chatgpt.org.uk" +MAIL_LINK_KEYWORDS = ("qwen", "verify", "activate", "confirm", "aliyun", "alibaba", "qwenlm") + +async def _extract_verify_link_from_page(page) -> str: + js_find_link = """() => { + const keywords = ['qwen', 'verify', 'activate', 'confirm', 'aliyun', 'alibaba', 'qwenlm']; + const links = Array.from(document.querySelectorAll('a[href]')); + for (const link of links) { + const href = link.href || ''; + const text = (link.textContent || '').toLowerCase(); + if (keywords.some((keyword) => href.toLowerCase().includes(keyword))) return href; + if (keywords.some((keyword) => text.includes(keyword)) && href.startsWith('http')) return href; + } + const html = document.body ? document.body.innerHTML : ''; + const matches = html.match(/https?:\\/\\/[^"'\\s<>\\\\]+/g) || []; + for (const match of matches) { + if (keywords.some((keyword) => match.toLowerCase().includes(keyword))) return match; + } + return null; + }""" + + try: + iframe_el = await page.query_selector('#emailFrame') + if iframe_el: + await asyncio.sleep(3) + frame = await iframe_el.content_frame() + if frame: + verify_link = await frame.evaluate(js_find_link) + if verify_link: + return verify_link + except Exception as e: + log.debug(f"[Activate] iframe read failed: {e}") + + try: + return await page.evaluate(js_find_link) or "" + except Exception: + return "" + +async def _find_verify_link_via_mail_page(email: str) -> str: + mail_url = f"{MAIL_BASE}/{email}" + try: + async with _new_browser() as browser: + page = await browser.new_page() + try: + await page.goto(mail_url, wait_until="networkidle", timeout=30000) + except Exception: + try: + await page.goto(mail_url, wait_until="domcontentloaded", timeout=15000) + except Exception: + pass + await asyncio.sleep(6) + + # Dismiss the site announcement modal if present; it intercepts pointer events. + try: + await page.evaluate("""() => { + const modal = document.querySelector('#siteAnnouncementModal'); + if (modal) { + modal.classList.remove('active'); + modal.setAttribute('aria-hidden', 'true'); + modal.style.display = 'none'; + modal.style.pointerEvents = 'none'; + } + document.querySelectorAll('.modal-overlay, .announcement-modal-overlay').forEach((el) => { + el.classList.remove('active'); + el.setAttribute('aria-hidden', 'true'); + el.style.display = 'none'; + el.style.pointerEvents = 'none'; + }); + }""") + await asyncio.sleep(0.5) + except Exception: + pass + + clicked_email = False + for sel in ['#emailList li:first-child', '#emailList li', '[class*="EmailItem"]', + '[class*="email-item"]', '[class*="MailItem"]', '[class*="mail-item"]', + 'table tbody tr:first-child', '[role="row"]:first-child']: + try: + await page.wait_for_selector(sel, timeout=10000) + el = await page.query_selector(sel) + if el: + await el.click(force=True) + await asyncio.sleep(4) + clicked_email = True + break + except Exception: + pass + + if not clicked_email: + for sel in ['li', 'tr', 'div[class]', '[class*="row"]', '[class*="item"]']: + try: + els = await page.query_selector_all(sel) + for el in (els or [])[:10]: + try: + text = await el.inner_text() + if any(keyword in text.lower() for keyword in MAIL_LINK_KEYWORDS): + await el.click(force=True) + await asyncio.sleep(4) + clicked_email = True + break + except Exception: + pass + if clicked_email: + break + except Exception: + pass + + return await _extract_verify_link_from_page(page) + except Exception as e: + log.warning(f"[Activate] mailbox page fallback failed for {email}: {e}") + return "" + +class _EmailSession: + def __init__(self): + from curl_cffi import requests as cffi_requests + self._session = cffi_requests.Session(impersonate="chrome") + self._session.headers.update({ + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0", + "accept-language": "zh-CN,zh;q=0.9,en;q=0.8", + }) + self._current_token = "" + self._token_expires_at = 0 + self._initialized = False + + def _init_session(self) -> bool: + try: + resp = self._session.get(f"{MAIL_BASE}/", timeout=15) + if resp.status_code != 200: + return False + match = re.search(r'window\.__BROWSER_AUTH\s*=\s*(\{[^}]+\})', resp.text) + if match: + auth_data = json.loads(match.group(1)) + self._current_token = auth_data.get("token", "") + self._token_expires_at = auth_data.get("expires_at", 0) + self._initialized = True + return True + # 新增获取 Token 的 fallback 逻辑 + resp = self._session.get(f"{MAIL_BASE}/api/auth/token", timeout=15) + if resp.status_code == 200: + auth_data = resp.json() + self._current_token = auth_data.get("token", "") + self._token_expires_at = auth_data.get("expires_at", 0) + self._initialized = True + return True + return False + except Exception as e: + log.warning(f"[MailSession] init error: {e}") + return False + + def _ensure_token(self) -> bool: + if not self._initialized or not self._current_token or time.time() > self._token_expires_at - 120: + return self._init_session() + return True + + def _set_auth(self, auth_data: dict): + if not isinstance(auth_data, dict): + return + new_tok = str(auth_data.get("token", "") or "").strip() + if new_tok: + self._current_token = new_tok + self._token_expires_at = int(auth_data.get("expires_at", 0) or 0) + self._initialized = bool(self._current_token) + + def _refresh_mailbox_token(self, email: str) -> bool: + email = str(email or "").strip().lower() + if not email: + return False + try: + resp = self._session.post( + f"{MAIL_BASE}/api/inbox-token", + json={"email": email}, + headers={"content-type": "application/json", "referer": f"{MAIL_BASE}/{email}"}, + timeout=15, + ) + if resp.status_code != 200: + return False + data = resp.json() + if not data.get("success") or not data.get("auth"): + return False + self._set_auth(data.get("auth", {})) + return bool(self._current_token) + except Exception as e: + log.warning(f"[MailSession] refresh mailbox token error for {email}: {e}") + return False + + def _extract_verify_link_from_email_record(self, msg: dict) -> str: + subject = str(msg.get("subject", "")) + parts = [] + for field in ("html_content", "content", "body", "html", "text", "raw"): + v = msg.get(field) + if v: + parts.append(str(v)) + for field in ("payload", "data", "message"): + v = msg.get(field) + if isinstance(v, dict): + parts.extend(str(x) for x in v.values() if x) + elif isinstance(v, str) and v: + parts.append(v) + combined = " ".join(parts) + combined = html_lib.unescape(combined) + combined = (combined.replace("\u003c", "<").replace("\u003e", ">") + .replace("\u0026", "&").replace("\\/", "/")) + + href_links = re.findall(r"href=[\"'](https?://[^\"']+)[\"']", combined, flags=re.IGNORECASE) + text_links = re.findall(r"https?://[^\s\"'<>\,\)]+", combined) + for link in href_links + text_links: + link = link.rstrip('.,;)') + if any(keyword in link.lower() for keyword in MAIL_LINK_KEYWORDS): + return link + if any(keyword in subject.lower() for keyword in MAIL_LINK_KEYWORDS): + for link in href_links + text_links: + if link.startswith('http'): + return link.rstrip('.,;)') + return "" + + def get_email(self) -> str: + if not self._ensure_token(): + raise Exception("mail.chatgpt.org.uk: session init failed") + resp = self._session.get( + f"{MAIL_BASE}/api/generate-email", + headers={"accept": "*/*", "referer": f"{MAIL_BASE}/", + "x-inbox-token": self._current_token}, + timeout=15, + ) + if resp.status_code == 401 or resp.status_code == 403: + self._initialized = False + self._init_session() + resp = self._session.get( + f"{MAIL_BASE}/api/generate-email", + headers={"accept": "*/*", "referer": f"{MAIL_BASE}/", + "x-inbox-token": self._current_token}, + timeout=15, + ) + data = resp.json() + if not data.get("success"): + raise Exception(f"mail.chatgpt.org.uk: generate-email failed: {data}") + email = str(data.get("data", {}).get("email", "")).strip() + new_tok = data.get("auth", {}).get("token", "") + if new_tok: + self._current_token = new_tok + self._token_expires_at = data.get("auth", {}).get("expires_at", 0) + return email + + def poll_verify_link(self, email: str, timeout_sec: int = 300) -> str: + email = str(email or "").strip().lower() + log.info(f"[MailSession] Polling inbox for {email} (timeout {timeout_sec}s)...") + deadline = time.time() + timeout_sec + attempt = 0 + while time.time() < deadline: + attempt += 1 + try: + if not self._refresh_mailbox_token(email): + if not self._ensure_token(): + time.sleep(2) + continue + + resp = self._session.get( + f"{MAIL_BASE}/api/emails", + params={"email": email}, + headers={ + "accept": "*/*", + "referer": f"{MAIL_BASE}/{email}", + "x-inbox-token": self._current_token, + }, + timeout=15, + ) + + if resp.status_code in (401, 403): + try: + data = resp.json() + except Exception: + data = {} + if data.get("auth"): + self._set_auth(data.get("auth", {})) + resp = self._session.get( + f"{MAIL_BASE}/api/emails", + params={"email": email}, + headers={ + "accept": "*/*", + "referer": f"{MAIL_BASE}/{email}", + "x-inbox-token": self._current_token, + }, + timeout=15, + ) + elif not self._refresh_mailbox_token(email): + time.sleep(2) + continue + else: + resp = self._session.get( + f"{MAIL_BASE}/api/emails", + params={"email": email}, + headers={ + "accept": "*/*", + "referer": f"{MAIL_BASE}/{email}", + "x-inbox-token": self._current_token, + }, + timeout=15, + ) + + if resp.status_code == 200: + data = resp.json() + if data.get("auth"): + self._set_auth(data.get("auth", {})) + emails_list = data.get("data", {}).get("emails", []) + log.info(f"[邮件] 第 {attempt} 次轮询,收到 {len(emails_list)} 封邮件") + for msg in emails_list: + link = self._extract_verify_link_from_email_record(msg) + if link: + log.info(f"[邮件] 找到验证链接:{link[:160]}...") + return link + else: + log.warning(f"[MailSession] email API HTTP {resp.status_code}: {resp.text[:120]}") + except Exception as e: + log.warning(f"[MailSession] poll error: {e}") + time.sleep(2) + log.error("[邮件] 轮询超时,未找到验证邮件") + return "" + +class _AsyncMailClient: + def __init__(self): + self._sess: Optional[_EmailSession] = None + self._email = "" + + async def __aenter__(self): + self._sess = await asyncio.to_thread(_EmailSession) + return self + + async def __aexit__(self, *args): + pass + + async def generate_email(self) -> str: + self._email = await asyncio.to_thread(self._sess.get_email) + return self._email + + async def get_verify_link(self, timeout_sec: int = 300) -> str: + return await asyncio.to_thread(self._sess.poll_verify_link, self._email, timeout_sec) + + async def get_verify_link_for_email(self, email: str, timeout_sec: int = 300) -> str: + return await asyncio.to_thread(self._sess.poll_verify_link, email, timeout_sec) + +async def register_qwen_account() -> Optional[Account]: + log.info("[Register] ── 开始注册流程 ──") + async with _AsyncMailClient() as mail_client: + log.info("[Register] [1/7] 生成临时邮箱...") + email = await mail_client.generate_email() + password = _gen_password() + username = _gen_username() + log.info(f"[Register] [1/7] 邮箱: {email} 用户名: {username}") + + try: + async with _new_browser() as browser: + page = await browser.new_page() + log.info(f"[Register] [2/7] 打开注册页面: {BASE_URL}/auth?action=signup") + try: + await page.goto(f"{BASE_URL}/auth?action=signup", wait_until="domcontentloaded", timeout=60000) + except Exception as e: + log.warning(f"[Register] [2/7] 页面加载异常: {e}") + + log.info("[Register] [3/7] 填写注册表单...") + name_input = None + for sel in ['input[placeholder*="Full Name"]', 'input[placeholder*="Name"]']: + try: + name_input = await page.wait_for_selector(sel, timeout=15000) + if name_input: break + except Exception: + pass + if not name_input: + inputs = await page.query_selector_all('input') + name_input = inputs[0] if len(inputs) >= 4 else None + if not name_input: + log.error("[Register] [3/7] 找不到姓名输入框,注册中止") + return None + + await name_input.click(); await name_input.fill(username) + log.info(f"[Register] [3/7] ✓ 姓名: {username}") + email_input = await page.query_selector('input[placeholder*="Email"]') + if not email_input: + inputs = await page.query_selector_all('input') + email_input = inputs[1] if len(inputs) >= 2 else None + if email_input: await email_input.click(); await email_input.fill(email) + log.info(f"[Register] [3/7] ✓ 邮箱: {email}") + + pwd_input = await page.query_selector('input[placeholder*="Password"]:not([placeholder*="Again"])') + if not pwd_input: + inputs = await page.query_selector_all('input') + pwd_input = inputs[2] if len(inputs) >= 3 else None + if pwd_input: await pwd_input.click(); await pwd_input.fill(password) + + confirm_input = await page.query_selector('input[placeholder*="Again"]') + if not confirm_input: + inputs = await page.query_selector_all('input') + confirm_input = inputs[3] if len(inputs) >= 4 else None + if confirm_input: await confirm_input.click(); await confirm_input.fill(password) + log.info("[Register] [3/7] ✓ 密码已填写") + + checkbox = await page.query_selector('input[type="checkbox"]') + if checkbox and not await checkbox.is_checked(): await checkbox.click() + else: + agree = await page.query_selector('text=I agree') + if agree: await agree.click() + log.info("[Register] [3/7] ✓ 同意条款") + + log.info("[Register] [4/7] 提交注册表单...") + await asyncio.sleep(1) + submit = await page.query_selector('button:has-text("Create Account")') or await page.query_selector('button[type="submit"]') + if submit: await submit.click() + log.info("[Register] [4/7] 已点击提交,等待页面跳转(6s)...") + await asyncio.sleep(6) + + url_after = page.url + log.info(f"[Register] [4/7] 提交后URL: {url_after}") + + # Check if already logged in (redirected to main page) + token = None + if BASE_URL in url_after and "auth" not in url_after: + log.info("[Register] [5/7] 已跳转主页,尝试直接获取token...") + await asyncio.sleep(3) + token = await page.evaluate("localStorage.getItem('token')") + if token: + log.info("[Register] [5/7] ✓ 注册后直接获取到token,跳过邮件验证") + + # If no token yet, try explicit login with email+password (faster than email poll) + if not token: + log.info("[Register] [5/7] 尝试用账号密码直接登录...") + try: + await page.goto(f"{BASE_URL}/auth", wait_until="domcontentloaded", timeout=30000) + await asyncio.sleep(3) + li_email = await page.query_selector('input[placeholder*="Email"]') + if li_email: await li_email.fill(email) + li_pwd = await page.query_selector('input[type="password"]') + if li_pwd: await li_pwd.fill(password) + li_btn = await page.query_selector('button:has-text("Log in")') or await page.query_selector('button[type="submit"]') + if li_btn: await li_btn.click() + await asyncio.sleep(8) + token = await page.evaluate("localStorage.getItem('token')") + if token: + log.info("[Register] [5/7] ✓ 直接登录成功,获取到token") + except Exception as e: + log.warning(f"[Register] [5/7] 直接登录失败: {e}") + + # If still no token, use mailbox email API first, then fall back to page lookup. + if not token: + log.info(f"[Register] [6/7] polling mailbox email API for {email}...") + verify_link = await mail_client.get_verify_link(timeout_sec=60) + if not verify_link: + log.info(f"[注册] [6/7] 邮件 API 未返回链接,尝试页面方式 {email}") + verify_link = await _find_verify_link_via_mail_page(email) + + if not verify_link: + log.error("[Register] [6/7] verification email not found") + return None + + log.info(f"[Register] [6/7] ✓ 收到验证链接,访问中...") + try: + await page.goto(verify_link, wait_until="domcontentloaded", timeout=30000) + except Exception: pass + await asyncio.sleep(6) + token = await page.evaluate("localStorage.getItem('token')") + log.info(f"[Register] [6/7] 验证后URL: {page.url}") + + # Login after verification + if not token: + log.info("[Register] [6/7] 验证链接后尝试登录...") + try: + await page.goto(f"{BASE_URL}/auth", wait_until="domcontentloaded", timeout=30000) + await asyncio.sleep(3) + li_email = await page.query_selector('input[placeholder*="Email"]') + if li_email: await li_email.fill(email) + li_pwd = await page.query_selector('input[type="password"]') + if li_pwd: await li_pwd.fill(password) + li_btn = await page.query_selector('button:has-text("Log in")') or await page.query_selector('button[type="submit"]') + if li_btn: await li_btn.click() + await asyncio.sleep(8) + token = await page.evaluate("localStorage.getItem('token')") + if token: + log.info("[Register] [6/7] ✓ 验证后登录成功") + except Exception: pass + + if not token: + log.error("[Register] 所有方法均无法获取token,注册失败") + return None + + log.info("[Register] [7/7] 提取 cookies...") + all_cookies = await page.context.cookies() + cookie_str = "; ".join(f"{c.get('name','')}={c.get('value','')}" for c in all_cookies if "qwen" in c.get("domain", "")) + log.info(f"[Register] ✓ 注册完成: {email}") + return Account(email=email, password=password, token=token, cookies=cookie_str, username=username, activation_pending=False) + except Exception as e: + import traceback + log.error(f"[Register] 注册异常: {e}\n{traceback.format_exc()}") + return None + +async def _login_and_get_token(page, email: str, password: str, timeout_sec: int = 20) -> str: + try: + await page.goto(f"{BASE_URL}/auth", wait_until="domcontentloaded", timeout=30000) + except Exception: + pass + await asyncio.sleep(2) + + email_input = None + pwd_input = None + try: + email_input = await page.query_selector('input[placeholder*="Email"]') + except Exception: + email_input = None + try: + pwd_input = await page.query_selector('input[type="password"]') + except Exception: + pwd_input = None + + if (not email_input) or (not pwd_input): + try: + inputs = await page.query_selector_all('input') + except Exception: + inputs = [] + text_inputs = [] + for item in inputs: + try: + t = await item.get_attribute('type') + except Exception: + t = None + if t in (None, '', 'text', 'email'): + text_inputs.append(item) + if not email_input and text_inputs: + email_input = text_inputs[0] + if not pwd_input: + for item in inputs: + try: + t = await item.get_attribute('type') + except Exception: + t = None + if t == 'password': + pwd_input = item + break + + if email_input: + try: + await email_input.click() + except Exception: + pass + await email_input.fill(email) + if pwd_input: + try: + await pwd_input.click() + except Exception: + pass + await pwd_input.fill(password) + + submit = None + for sel in [ + 'button:has-text("Log in")', + 'button[type="submit"]:not([disabled])', + 'button[type="submit"]', + 'button:has-text("Continue")', + ]: + try: + submit = await page.query_selector(sel) + if submit: + disabled = await submit.get_attribute('disabled') + aria_disabled = await submit.get_attribute('aria-disabled') + if disabled is None and aria_disabled not in ('true', 'disabled'): + break + except Exception: + pass + + clicked = False + if submit: + try: + await submit.click(timeout=5000) + clicked = True + except Exception: + try: + await submit.click(force=True, timeout=3000) + clicked = True + except Exception: + pass + + if not clicked and pwd_input: + try: + await pwd_input.press('Enter') + except Exception: + pass + + deadline = time.time() + timeout_sec + while time.time() < deadline: + try: + token = await page.evaluate("localStorage.getItem('token')") + except Exception: + token = None + if token: + return token + await asyncio.sleep(1) + return "" + +async def activate_account(acc: Account) -> bool: + """Use inbox API first, then mailbox-page fallback, to activate an account.""" + started_at = float(getattr(acc, "_activation_started_at", 0) or 0) + if getattr(acc, "_is_activating", False): + if started_at and (time.time() - started_at) < 90: + log.info(f"[激活] {acc.email} 正在激活中,跳过重复调用") + return acc.valid and not acc.activation_pending + log.warning(f"[激活] {acc.email} 激活超时,重置激活标志重新尝试") + setattr(acc, "_is_activating", False) + + log.info(f"[激活] 开始激活账号 {acc.email}") + setattr(acc, "_is_activating", True) + setattr(acc, "_activation_started_at", time.time()) + try: + verify_link = "" + try: + async with _AsyncMailClient() as mail_client: + verify_link = await mail_client.get_verify_link_for_email(acc.email, timeout_sec=30) + except Exception as e: + log.warning(f"[激活] {acc.email} 邮件 API 失败: {e}") + + if not verify_link: + log.info(f"[激活] {acc.email} 邮件 API 未返回链接,使用页面方式") + verify_link = await _find_verify_link_via_mail_page(acc.email) + + if not verify_link: + log.warning(f"[Activate] activation email not found for {acc.email}") + return False + + log.info(f"[激活] {acc.email} 找到验证链接:{verify_link[:120]}") + + async with _new_browser() as browser: + page = await browser.new_page() + try: + await page.goto(verify_link, wait_until="networkidle", timeout=30000) + except Exception: + try: + await page.goto(verify_link, wait_until="domcontentloaded", timeout=15000) + except Exception: + pass + + await asyncio.sleep(5) + token = await page.evaluate("localStorage.getItem('token')") + log.info(f"[激活] {acc.email} 访问验证链接后 URL={page.url},Token:{'有' if token else '无'}") + + if not token and acc.password: + try: + token = await _login_and_get_token(page, acc.email, acc.password, timeout_sec=20) + except Exception as e: + log.warning(f"[激活] {acc.email} 登录获取 token 失败: {e}") + + if token: + acc.token = token + acc.valid = True + acc.activation_pending = False + log.info(f"[激活] {acc.email} 激活成功") + return True + + # Some activation links make the original token usable again without issuing a new one. + if await _verify_qwen_token(acc.token): + acc.valid = True + acc.activation_pending = False + log.info(f"[激活] {acc.email} 旧 Token 仍然有效,激活完成") + return True + + log.warning(f"[激活] {acc.email} 激活失败,无法获取 Token") + return False + except Exception as e: + log.error(f"[激活] {acc.email} 激活异常: {e}") + return False + finally: + setattr(acc, "_is_activating", False) + setattr(acc, "_activation_started_at", 0) + +class AuthResolver: + """自动登录并提取 Token,在检测到 401 时自动自愈凭证""" + def __init__(self, pool: AccountPool): + self.pool = pool + + async def auto_heal_account(self, acc: Account): + """Background task to refresh token. If successful, marks account valid. + If refresh fails or account is pending activation, tries to activate via email.""" + if getattr(acc, "healing", False): + log.info(f"[BGRefresh] {acc.email} healing already in progress") + return + + acc.healing = True + try: + ok = await self.refresh_token(acc) + if ok: + if not getattr(acc, 'activation_pending', False): + acc.valid = True + await self.pool.save() + log.info(f"[自愈] {acc.email} Token 刷新成功,已标记有效") + return + log.info(f"[BGRefresh] {acc.email} token refreshed but account still needs activation") + else: + log.warning(f"[自愈] {acc.email} Token 刷新失败,尝试激活") + + activated = await activate_account(acc) + if activated: + acc.activation_pending = False + acc.valid = True + await self.pool.save() + log.info(f"[自愈] {acc.email} 激活成功,已保存") + else: + log.warning(f"[自愈] {acc.email} 激活失败") + except Exception as e: + log.warning(f"[BGRefresh] {acc.email} auto heal failed: {e}") + finally: + acc.healing = False + + async def refresh_token(self, acc: Account) -> bool: + + """Re-login with email+password to get a fresh token. Returns True on success.""" + if not acc.email or not acc.password: + log.warning(f"[Refresh] 账号 {acc.email} 无密码,无法刷新") + return False + + log.info(f"[Refresh] 正在为 {acc.email} 刷新 token...") + try: + async with _new_browser() as browser: + page = await browser.new_page() + new_token = await _login_and_get_token(page, acc.email, acc.password, timeout_sec=20) + if new_token and new_token != acc.token: + old_prefix = acc.token[:20] if acc.token else "空" + acc.token = new_token + acc.valid = True + await self.pool.save() + log.info(f"[Refresh] {acc.email} token 已更新 ({old_prefix}... → {new_token[:20]}...)") + return True + elif new_token == acc.token: + # Token same but might still be valid — mark valid again + acc.valid = True + log.info(f"[Refresh] {acc.email} token 未变化,重新标记有效") + return True + else: + log.warning(f"[Refresh] {acc.email} 登录后未获取到token,URL={page.url}") + return False + except Exception as e: + log.error(f"[Refresh] {acc.email} 刷新异常: {e}") + return False diff --git a/backend/services/chat_id_pool.py b/backend/services/chat_id_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..f08b89658f8540a96046a2df21a4f0812537a0f8 --- /dev/null +++ b/backend/services/chat_id_pool.py @@ -0,0 +1,188 @@ +"""Chat ID 预热池:预先为每个可用账号创建若干 chat_id 放在队列里, +请求到来时直接从队列 pop 一个省去 /chats/new 握手(实测 500ms~6s 不等)。 + +典型收益:每次请求节省 500~3000ms 握手时延;最坏情况抖动时节省 5~6s。 + +工作流: +- 服务启动 → 每账号预建 target_per_account 个 chat_id +- 请求用掉一个 chat_id → 后台立即补位一个 +- 每账号池大小上限:target_per_account (默认 3) +- chat_id 有 TTL (默认 30 分钟),超时背景任务丢弃+重建 +- 请求取不到预热 chat_id 时:fallback 到同步 create_chat(当前行为) +""" + +from __future__ import annotations + +import asyncio +import logging +import time +from collections import deque +from typing import Any, Optional + +log = logging.getLogger("qwen2api.chat_pool") + + +class _Entry: + __slots__ = ("chat_id", "created_at") + + def __init__(self, chat_id: str): + self.chat_id = chat_id + self.created_at = time.time() + + +class ChatIdPool: + """按账号邮箱 key 的 chat_id 队列。线程/协程安全。""" + + def __init__( + self, + client, + *, + target_per_account: int = 5, + ttl_seconds: float = 10 * 60, + default_model: str = "qwen3.6-plus", + ): + self._client = client + self._target = target_per_account + self._ttl = ttl_seconds + self._default_model = default_model + self._queues: dict[str, deque[_Entry]] = {} + self._lock = asyncio.Lock() + self._refill_task: Optional[asyncio.Task] = None + self._shutdown = False + + @property + def target(self) -> int: + return self._target + + @property + def ttl(self) -> float: + return self._ttl + + def update_config(self, *, target: int | None = None, ttl_seconds: float | None = None) -> None: + """运行时热更新参数。target 调小会在下一轮 refill 时把多余的 chat_id 丢掉; + 调大会在下一轮补位时扩容。TTL 变化影响下一次 acquire 的过期判断。""" + if target is not None: + self._target = max(0, int(target)) + if ttl_seconds is not None: + self._ttl = max(30.0, float(ttl_seconds)) + log.info(f"[ChatIdPool] config updated target={self._target} ttl={self._ttl}s") + + async def start(self) -> None: + """服务启动时调用,完成首轮预热 + 启动后台补位 loop。""" + # 初次预热 & 启动补位 loop + self._refill_task = asyncio.create_task(self._refill_loop()) + log.info(f"[ChatIdPool] started (target={self._target}, ttl={self._ttl}s)") + + async def stop(self) -> None: + self._shutdown = True + if self._refill_task: + self._refill_task.cancel() + try: + await self._refill_task + except (asyncio.CancelledError, Exception): + pass + + async def acquire(self, email: str, model: str | None = None) -> Optional[str]: + """优先从预热池取 chat_id;池空或过期则返回 None(调用方走同步 create_chat)。""" + if not email: + return None + async with self._lock: + q = self._queues.get(email) + if not q: + return None + now = time.time() + while q: + entry = q.popleft() + if now - entry.created_at < self._ttl: + log.debug(f"[ChatIdPool] HIT email={email} chat_id={entry.chat_id}") + return entry.chat_id + # 过期就丢弃继续找下一个 + log.debug(f"[ChatIdPool] expired chat_id={entry.chat_id} email={email}") + return None + + async def _prewarm_one(self, account, model: str) -> None: + """为某账号预建一个 chat_id 加入队列。""" + try: + token = account.token + email = account.email + if not token: + log.warning(f"[ChatIdPool] prewarm skipped email={email}: missing token") + return + chat_id = await self._client.executor.create_chat(token, model) + async with self._lock: + q = self._queues.setdefault(email, deque()) + q.append(_Entry(chat_id)) + log.info(f"[ChatIdPool] prewarmed email={email} chat_id={chat_id} pool_size={len(q)}") + except Exception as e: + # Make sure empty-string exceptions still show class name + err = str(e) or type(e).__name__ + log.warning(f"[ChatIdPool] prewarm failed email={getattr(account, 'email', '?')}: {err}") + + async def _refill_loop(self) -> None: + """定期轮询:每账号池低于 target 则补位。 + 注:5 分钟一轮,太频繁的 /chats/new 会被 Qwen 风控降级为空 SSE。""" + interval = 300.0 + # 初始化立即跑一轮 + await asyncio.sleep(1.0) + while not self._shutdown: + try: + await self._refill_once() + except Exception as e: + log.warning(f"[ChatIdPool] refill error: {e}") + await asyncio.sleep(interval) + + async def _refill_once(self) -> None: + """遍历账号池里所有 valid 账号,每个不足 target 就补位。""" + pool = getattr(self._client, "account_pool", None) + if pool is None: + return + all_accounts = getattr(pool, "accounts", []) or [] + + # 只对有 token + 状态 valid 的账号预热 + valid = [a for a in all_accounts if getattr(a, "token", "") and getattr(a, "status_code", "valid") == "valid"] + + for acc in valid: + async with self._lock: + q_size = len(self._queues.get(acc.email, [])) + deficit = self._target - q_size + # 每轮每账号最多补 1 个,避免突发 API 压力 + if deficit > 0: + await self._prewarm_one(acc, self._default_model) + + async def invalidate(self, email: str, chat_id: str) -> None: + """标记某个 chat_id 为坏的——从池里移除,防止下次又被取到。 + + 用于上游返回空响应 / 5xx / 超时后的清理。""" + if not email or not chat_id: + return + async with self._lock: + q = self._queues.get(email) + if not q: + return + remaining = deque(e for e in q if e.chat_id != chat_id) + self._queues[email] = remaining + if len(remaining) != len(q): + log.info(f"[ChatIdPool] invalidated email={email} chat_id={chat_id}") + + async def flush_account(self, email: str) -> int: + """把某账号池里的所有 chat_id 清空。用于该账号命中空响应/5xx 后的保守处理, + 防止同批次预热的其他 chat_id 也是坏的。返回清理数量。""" + if not email: + return 0 + async with self._lock: + q = self._queues.get(email) + if not q: + return 0 + n = len(q) + self._queues[email] = deque() + if n: + log.info(f"[ChatIdPool] flushed {n} entries for email={email}") + return n + + async def size(self, email: str) -> int: + async with self._lock: + return len(self._queues.get(email, [])) + + async def total_size(self) -> int: + async with self._lock: + return sum(len(q) for q in self._queues.values()) diff --git a/backend/services/client_profiles.py b/backend/services/client_profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..1735028be3197313f0d51f1f798336ce59e6419a --- /dev/null +++ b/backend/services/client_profiles.py @@ -0,0 +1,321 @@ +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import Any + +CLAUDE_CODE_OPENAI_PROFILE = "claude_code_openai" +OPENCLAW_OPENAI_PROFILE = "openclaw_openai" +QWEN_CODE_OPENAI_PROFILE = "qwen_code_openai" + +OPENCLAW_STARTUP_PATTERNS = ( + "A new session was started via /new or /reset.", + "If runtime-provided startup context is included for this first turn", +) +OPENCLAW_UNTRUSTED_METADATA_PREFIX = "Sender (untrusted metadata):" +OPENCODE_SYSTEM_PREFIX = "you are opencode" + +QWEN_CODE_SYSTEM_HINTS = ("qwen code", "qwen-code", "you are qwen code", "you are qwen-code") +QWEN_CODE_OPENAI_TOOL_NAMES = frozenset({ + "read_file", + "list_directory", + "write_file", + "run_shell_command", +}) +QWEN_CODE_PROFILE_TOOL_HINTS = { + "readfile", + "writefile", + "editfile", + "listdirectory", + "listdir", + "listfiles", + "runshellcommand", + "runcommand", +} +QWEN_CODE_TOOL_HINTS = { + "read", + "write", + "edit", + "multiedit", + "notebookedit", + "grep", + "glob", + "bash", + "readfile", + "writefile", + "editfile", + "notebookeditcell", + "runcommand", + "execcommand", + "listdirectory", + "listdir", + "listfiles", + "searchfiles", +} +QWEN_CODE_FILE_TOOL_HINTS = { + "read", + "write", + "edit", + "multiedit", + "notebookedit", + "readfile", + "writefile", + "editfile", +} +QWEN_CODE_NAV_TOOL_HINTS = { + "grep", + "glob", + "bash", + "runcommand", + "execcommand", + "listdirectory", + "listdir", + "listfiles", + "searchfiles", +} +QWEN_CODE_TASK_REGEX = re.compile( + r"(code|coding|program|repo|repository|refactor|debug|fix|implement|patch|file|files|terminal|shell|bash|command|test|build|编程|代码|仓库|文件|脚本|命令|调试|修复|实现|重构|测试)", + re.IGNORECASE, +) +QWEN_CODE_OPENAI_HINT_HEADERS = ( + "user-agent", + "x-openai-client-user-agent", + "x-client-user-agent", +) +OPENAI_SDK_FINGERPRINT_HEADERS = ( + "x-openai-client-user-agent", + "x-stainless-lang", + "x-stainless-package-version", + "x-stainless-runtime", +) + + +def header_value(headers: Mapping[str, Any] | Any, header_name: str) -> str: + value = "" + if hasattr(headers, "get"): + value = headers.get(header_name, "") + elif isinstance(headers, Mapping): + value = headers.get(header_name, "") + if isinstance(value, str): + return value + if value is None: + return "" + return str(value) + + +def normalized_tool_name(value: str) -> str: + return re.sub(r"[^a-z0-9]+", "", str(value or "").strip().lower()) + + +def normalize_tool(tool: dict[str, Any]) -> dict[str, Any]: + if tool.get("type") == "function" and "function" in tool: + fn = tool["function"] + return { + "name": fn.get("name", ""), + "description": fn.get("description", ""), + "parameters": fn.get("parameters", {}), + } + return { + "name": tool.get("name", ""), + "description": tool.get("description", ""), + "parameters": tool.get("input_schema") or tool.get("parameters") or {}, + } + + +def normalize_tools(tools: list[Any] | None) -> list[dict[str, Any]]: + return [normalize_tool(tool) for tool in (tools or []) if isinstance(tool, dict)] + + +def extract_declared_tool_names(req_data: dict[str, Any] | None) -> set[str]: + if not isinstance(req_data, dict): + return set() + + tool_names: set[str] = set() + for tool in req_data.get("tools", []) or []: + if not isinstance(tool, dict): + continue + candidate = tool.get("name") + if not isinstance(candidate, str) or not candidate.strip(): + function_payload = tool.get("function") + if isinstance(function_payload, dict): + candidate = function_payload.get("name") + if isinstance(candidate, str) and candidate.strip(): + tool_names.add(candidate.strip().lower()) + return tool_names + + +def has_qwen_code_header_hint(headers: Mapping[str, Any] | Any) -> bool: + for header_name in QWEN_CODE_OPENAI_HINT_HEADERS: + value = header_value(headers, header_name).lower() + if "qwen" in value and "code" in value: + return True + return False + + +def has_openai_sdk_fingerprint(headers: Mapping[str, Any] | Any) -> bool: + return any(header_value(headers, header_name) for header_name in OPENAI_SDK_FINGERPRINT_HEADERS) + + +def is_qwen_code_openai_request(headers: Mapping[str, Any] | Any, req_data: dict[str, Any] | None) -> bool: + tool_names = extract_declared_tool_names(req_data) + qwen_tool_matches = len(tool_names & QWEN_CODE_OPENAI_TOOL_NAMES) + if qwen_tool_matches >= len(QWEN_CODE_OPENAI_TOOL_NAMES): + return True + if qwen_tool_matches >= 3 and (has_qwen_code_header_hint(headers) or has_openai_sdk_fingerprint(headers)): + return True + return has_qwen_code_header_hint(headers) + + +def sanitize_openclaw_user_text(text: str) -> str: + cleaned = text.strip() + if not cleaned: + return cleaned + if any(marker in cleaned for marker in OPENCLAW_STARTUP_PATTERNS): + return "" + if cleaned.startswith(OPENCLAW_UNTRUSTED_METADATA_PREFIX): + match = re.search(r"\n\n(\[[^\n]+\]\s*[\s\S]*)$", cleaned) + if match: + cleaned = match.group(1).strip() + else: + return "" + return cleaned + + +def extract_user_text_only(content: Any, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> str: + if isinstance(content, str): + return sanitize_openclaw_user_text(content) if client_profile == OPENCLAW_OPENAI_PROFILE else content + if not isinstance(content, list): + return "" + + text_blocks: list[str] = [] + for part in content: + if not isinstance(part, dict) or part.get("type", "") != "text": + continue + block_text = part.get("text", "") + if client_profile == OPENCLAW_OPENAI_PROFILE: + block_text = sanitize_openclaw_user_text(block_text) + if block_text: + text_blocks.append(block_text) + return "\n".join(text_blocks) + + +def extract_system_prompt(req_data: dict[str, Any], *, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> str: + system_prompt = "" + sys_field = req_data.get("system", "") + if isinstance(sys_field, list): + system_prompt = " ".join( + part.get("text", "") + for part in sys_field + if isinstance(part, dict) + ) + elif isinstance(sys_field, str): + system_prompt = sys_field + + if system_prompt: + return system_prompt + + for msg in req_data.get("messages", []) or []: + if msg.get("role") == "system": + return extract_user_text_only(msg.get("content", ""), client_profile=client_profile) + return "" + + +def looks_like_opencode_system_prompt(system_prompt: str) -> bool: + if not isinstance(system_prompt, str): + return False + return system_prompt.strip().lower().startswith(OPENCODE_SYSTEM_PREFIX) + + +def extract_latest_user_text( + messages: list[dict[str, Any]] | None, + *, + client_profile: str = OPENCLAW_OPENAI_PROFILE, +) -> str: + for msg in reversed(messages or []): + if msg.get("role") != "user": + continue + text = extract_user_text_only(msg.get("content", ""), client_profile=client_profile).strip() + if text: + return text + return "" + + +def request_looks_like_coding_task( + req_data: dict[str, Any], + *, + client_profile: str = OPENCLAW_OPENAI_PROFILE, +) -> bool: + normalized_tools = normalize_tools(req_data.get("tools", [])) + normalized_names = { + normalized_tool_name(tool.get("name", "")) + for tool in normalized_tools + if tool.get("name") + } + latest_user_text = extract_latest_user_text( + req_data.get("messages", []), + client_profile=client_profile, + ) + if len(normalized_names & QWEN_CODE_FILE_TOOL_HINTS) >= 1 and len(normalized_names & QWEN_CODE_NAV_TOOL_HINTS) >= 1: + return True + if len(normalized_names & QWEN_CODE_TOOL_HINTS) >= 3: + return True + return bool(latest_user_text and QWEN_CODE_TASK_REGEX.search(latest_user_text)) + + +def infer_client_profile( + req_data: dict[str, Any], + *, + fallback_profile: str = OPENCLAW_OPENAI_PROFILE, +) -> str: + if fallback_profile in {CLAUDE_CODE_OPENAI_PROFILE, QWEN_CODE_OPENAI_PROFILE}: + return fallback_profile + + system_prompt = extract_system_prompt(req_data, client_profile=fallback_profile) + system_lower = system_prompt.strip().lower() + if looks_like_opencode_system_prompt(system_prompt): + return fallback_profile + if any(hint in system_lower for hint in QWEN_CODE_SYSTEM_HINTS): + return QWEN_CODE_OPENAI_PROFILE + + normalized_names = { + normalized_tool_name(tool.get("name", "")) + for tool in normalize_tools(req_data.get("tools", [])) + if tool.get("name") + } + qwen_code_tool_matches = normalized_names & QWEN_CODE_PROFILE_TOOL_HINTS + if len(qwen_code_tool_matches) >= 3: + return QWEN_CODE_OPENAI_PROFILE + if len(qwen_code_tool_matches) >= 2 and request_looks_like_coding_task(req_data, client_profile=fallback_profile): + return QWEN_CODE_OPENAI_PROFILE + return fallback_profile + + +def detect_openai_client_profile(headers: Mapping[str, Any] | Any, req_data: dict[str, Any] | None) -> str: + if header_value(headers, "x-anthropic-billing-header"): + return CLAUDE_CODE_OPENAI_PROFILE + if is_qwen_code_openai_request(headers, req_data): + return QWEN_CODE_OPENAI_PROFILE + return OPENCLAW_OPENAI_PROFILE + + +__all__ = [ + "CLAUDE_CODE_OPENAI_PROFILE", + "OPENCLAW_OPENAI_PROFILE", + "QWEN_CODE_OPENAI_PROFILE", + "detect_openai_client_profile", + "extract_declared_tool_names", + "extract_latest_user_text", + "extract_system_prompt", + "extract_user_text_only", + "has_openai_sdk_fingerprint", + "has_qwen_code_header_hint", + "header_value", + "infer_client_profile", + "is_qwen_code_openai_request", + "looks_like_opencode_system_prompt", + "normalize_tool", + "normalize_tools", + "normalized_tool_name", + "request_looks_like_coding_task", + "sanitize_openclaw_user_text", +] diff --git a/backend/services/completion_bridge.py b/backend/services/completion_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..d70a306460d41dfba432058126168daa6acaa392 --- /dev/null +++ b/backend/services/completion_bridge.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +from typing import Any, Awaitable, Callable + +from backend.adapter.standard_request import StandardRequest +from backend.runtime.execution import build_tool_directive, cleanup_runtime_resources, collect_completion_run, evaluate_retry_directive +from backend.services.auth_quota import add_used_tokens +from backend.services.task_session import build_retry_rebase_prompt +from backend.services.token_calc import calculate_usage + + +@dataclass(slots=True) +class CompletionBridgeResult: + execution: Any + usage: dict[str, int] + prompt: str + attempt_index: int + directive: Any | None = None + + +async def _reacquire_bound_account_if_needed(*, client, standard_request: StandardRequest) -> None: + preferred_email = getattr(standard_request, 'bound_account_email', None) + if preferred_email: + standard_request.bound_account = await client.account_pool.acquire_wait_preferred(preferred_email, timeout=60) + else: + standard_request.bound_account = None + + +async def run_completion_bridge( + *, + client, + standard_request: StandardRequest, + prompt: str, + users_db, + token: str, + usage_delta: int | None = None, + capture_events: bool = True, + on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None, +) -> CompletionBridgeResult: + execution = await collect_completion_run( + client, + standard_request, + prompt, + capture_events=capture_events, + on_delta=on_delta, + ) + usage = calculate_usage(prompt, execution.state.answer_text) + await add_used_tokens(users_db, token, usage_delta if usage_delta is not None else usage["total_tokens"]) + await cleanup_runtime_resources( + client, + execution.acc, + execution.chat_id, + preserve_chat=bool(getattr(standard_request, 'persistent_session', False)), + ) + return CompletionBridgeResult(execution=execution, usage=usage, prompt=prompt, attempt_index=0) + + +async def run_retryable_completion_bridge( + *, + client, + standard_request: StandardRequest, + prompt: str, + users_db, + token: str, + history_messages: list[dict[str, Any]] | None, + max_attempts: int, + usage_delta_factory: Callable[[Any, str], int] | None = None, + allow_after_visible_output: bool = False, + capture_events: bool = True, + on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None, +) -> CompletionBridgeResult: + current_prompt = prompt + if not getattr(standard_request, 'full_prompt', None): + standard_request.full_prompt = prompt + + for attempt_index in range(max_attempts): + execution = await collect_completion_run( + client, + standard_request, + current_prompt, + capture_events=capture_events, + on_delta=on_delta, + ) + retry = evaluate_retry_directive( + request=standard_request, + current_prompt=current_prompt, + history_messages=history_messages, + attempt_index=attempt_index, + max_attempts=max_attempts, + state=execution.state, + allow_after_visible_output=allow_after_visible_output, + ) + if retry.retry: + preserve_chat = bool(getattr(standard_request, 'persistent_session', False)) + await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat) + + reused_persistent_chat = bool(getattr(standard_request, 'persistent_session', False) and getattr(standard_request, 'upstream_chat_id', None)) + if reused_persistent_chat: + current_prompt = build_retry_rebase_prompt(standard_request, reason=retry.reason) + else: + current_prompt = retry.next_prompt + + if not preserve_chat: + await asyncio.sleep(0.15) + await _reacquire_bound_account_if_needed(client=client, standard_request=standard_request) + continue + + usage = calculate_usage(current_prompt, execution.state.answer_text) + usage_delta = usage_delta_factory(execution, current_prompt) if usage_delta_factory is not None else usage["total_tokens"] + directive = build_tool_directive(standard_request, execution.state) + await add_used_tokens(users_db, token, usage_delta) + await cleanup_runtime_resources( + client, + execution.acc, + execution.chat_id, + preserve_chat=bool(getattr(standard_request, 'persistent_session', False)), + ) + return CompletionBridgeResult( + execution=execution, + usage=usage, + prompt=current_prompt, + attempt_index=attempt_index, + directive=directive, + ) + + raise RuntimeError("Retryable completion bridge exhausted attempts") diff --git a/backend/services/context_attachment_manager.py b/backend/services/context_attachment_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..a392f1a6cb9b80633cbcdcbf2b4ea257d840d65b --- /dev/null +++ b/backend/services/context_attachment_manager.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Any + +from backend.core.upstream_file_cache import UpstreamFileCacheEntry +from backend.services.context_offload import SYSTEM_CONTEXT_FILE_PREFIX, SYSTEM_CONTEXT_PROMPT_NOTE + + +def derive_session_key(surface: str, auth_token: str, payload: dict[str, Any]) -> str: + explicit = (payload.get("session_key") or payload.get("conversation_id") or payload.get("metadata", {}).get("conversation_id") if isinstance(payload.get("metadata"), dict) else None) + if explicit: + return str(explicit) + first_user = next((m for m in payload.get("messages", []) if m.get("role") == "user"), {}) + content = first_user.get("content", "") + if isinstance(content, list): + first_text = "\n".join(str(part.get("text", "")) for part in content if isinstance(part, dict) and part.get("type") == "text") + else: + first_text = str(content) + basis = f"{surface}::{auth_token}::{payload.get('model', '')}::{first_text[:400]}" + return hashlib.sha256(basis.encode("utf-8", errors="ignore")).hexdigest()[:24] + + +async def prepare_context_attachments(*, app, payload: dict[str, Any], surface: str, auth_token: str, client_profile: str, existing_attachments=None) -> dict[str, Any]: + context_offloader = app.state.context_offloader + account_pool = app.state.account_pool + file_store = app.state.file_store + affinity = app.state.session_affinity + cache = app.state.upstream_file_cache + uploader = app.state.upstream_file_uploader + + session_key = derive_session_key(surface, auth_token, payload) + tools = payload.get("tools", []) or [] + messages = payload.get("messages", []) or [] + manual_attachments = list(existing_attachments or []) + plan = context_offloader.plan(messages, tools=tools, client_profile=client_profile) + use_generated_context_files = bool(plan.generated_files) and not bool(tools) + if not use_generated_context_files and not manual_attachments: + return { + "payload": payload, + "session_key": session_key, + "context_mode": "inline", + "upstream_files": list(payload.get("upstream_files", []) or []), + "bound_account": None, + "bound_account_email": None, + "generated_local_files": [], + "attachment_fallback": False, + } + + record = await affinity.get(session_key) + preferred_email = record.account_email if record else None + acc = await account_pool.acquire_wait_preferred(preferred_email, timeout=60) + if not acc: + raise RuntimeError("No available upstream account for context attachment mode") + await affinity.bind_account(session_key, surface, acc.email, context_offloader.settings.CONTEXT_ATTACHMENT_TTL_SECONDS) + + upstream_files = list(payload.get("upstream_files", []) or []) + local_file_records: list[dict[str, Any]] = [] + + try: + for attachment in manual_attachments: + if getattr(attachment, "remote_ref", None): + upstream_files.append(attachment.remote_ref) + continue + if not attachment.local_path: + continue + local_meta = { + "id": attachment.file_id, + "path": attachment.local_path, + "filename": attachment.filename, + "content_type": attachment.content_type, + "sha256": attachment.sha256, + "created_at": __import__("time").time(), + } + ext = Path(attachment.filename).suffix.lstrip(".").lower() + cache_entry = await cache.get(session_key, acc.email, local_meta["sha256"], ext) + if cache_entry is not None: + remote = cache_entry.remote_file_meta + else: + remote = await uploader.upload_local_file(acc, local_meta) + await cache.set(UpstreamFileCacheEntry( + session_key=session_key, + account_email=acc.email, + sha256=local_meta["sha256"], + ext=ext, + filename=attachment.filename, + remote_file_meta=remote, + created_at=local_meta["created_at"], + expires_at=local_meta["created_at"] + context_offloader.settings.CONTEXT_ATTACHMENT_TTL_SECONDS, + )) + upstream_files.append(remote["remote_ref"]) + await affinity.add_uploaded_file(session_key, remote) + await file_store.delete_path(attachment.local_path) + + if use_generated_context_files: + for index, generated in enumerate(plan.generated_files, 1): + fixed_base = f"{SYSTEM_CONTEXT_FILE_PREFIX}_{index}" if len(plan.generated_files) > 1 else SYSTEM_CONTEXT_FILE_PREFIX + filename = f"{fixed_base}.{generated.ext}" + local_meta = await file_store.save_text(filename, generated.text, generated.content_type, purpose="context") + cache_entry = await cache.get(session_key, acc.email, local_meta["sha256"], generated.ext) + if cache_entry is not None: + remote = cache_entry.remote_file_meta + else: + remote = await uploader.upload_local_file(acc, local_meta) + await cache.set(UpstreamFileCacheEntry( + session_key=session_key, + account_email=acc.email, + sha256=local_meta["sha256"], + ext=generated.ext, + filename=filename, + remote_file_meta=remote, + created_at=local_meta["created_at"], + expires_at=local_meta["created_at"] + context_offloader.settings.CONTEXT_ATTACHMENT_TTL_SECONDS, + )) + upstream_files.append(remote["remote_ref"]) + await affinity.add_uploaded_file(session_key, remote) + await file_store.delete_path(local_meta["path"]) + local_file_records.append(local_meta) + except Exception: + account_pool.release(acc) + fallback_payload = dict(payload) + summary_parts: list[str] = [] + if use_generated_context_files and plan.summary_text: + summary_parts.append(plan.summary_text[:1200]) + if manual_attachments: + names = ", ".join(att.filename for att in manual_attachments[:4]) + summary_parts.append(f"User attachments were provided but attachment upload failed. Attachment names: {names}") + latest_text = summary_parts[0] if summary_parts else "Attachment upload failed. Continue with the available inline context only." + fallback_payload["messages"] = [{ + "role": "user", + "content": f"{latest_text}\n\n{SYSTEM_CONTEXT_PROMPT_NOTE}" + }] + return { + "payload": fallback_payload, + "session_key": session_key, + "context_mode": "inline", + "upstream_files": list(payload.get("upstream_files", []) or []), + "bound_account": None, + "bound_account_email": None, + "generated_local_files": [], + "attachment_fallback": True, + } + + rewritten = dict(payload) + rewritten["messages"] = plan.inline_messages if use_generated_context_files else messages + return { + "payload": rewritten, + "session_key": session_key, + "context_mode": plan.mode if use_generated_context_files else "inline", + "upstream_files": upstream_files, + "bound_account": acc, + "bound_account_email": acc.email, + "generated_local_files": local_file_records, + "attachment_fallback": False, + } diff --git a/backend/services/context_cleanup.py b/backend/services/context_cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..6387038fa4b12f0f1d6b1e712478a6bd61cfaa5e --- /dev/null +++ b/backend/services/context_cleanup.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import asyncio +import logging + +from backend.core.request_logging import request_context + +log = logging.getLogger("qwen2api.context_cleanup") + + +async def context_cleanup_loop(app, interval_seconds: int = 300): + while True: + try: + with request_context(surface="context-cleanup"): + ttl = app.state.context_offloader.settings.CONTEXT_ATTACHMENT_TTL_SECONDS + await app.state.file_store.cleanup_expired(ttl) + expired_records = await app.state.session_affinity.cleanup_expired() + await app.state.upstream_file_cache.cleanup_expired() + for record in expired_records: + acc = app.state.account_pool.get_by_email(record.account_email) + if not acc: + continue + if record.chat_id: + try: + await app.state.qwen_client.delete_chat(acc.token, record.chat_id) + except Exception as exc: + log.debug("[ContextCleanup] chat delete failed session=%s chat_id=%s error=%s", record.session_key, record.chat_id, exc) + for remote_meta in record.uploaded_files: + try: + await app.state.upstream_file_uploader.delete_remote_file(acc, remote_meta) + except Exception as exc: + log.debug("[ContextCleanup] remote delete failed session=%s error=%s", record.session_key, exc) + log.info("[ContextCleanup] ttl=%s expired_sessions=%s completed", ttl, len(expired_records)) + except Exception as exc: + log.warning("[ContextCleanup] failed: %s", exc) + await asyncio.sleep(max(60, interval_seconds)) diff --git a/backend/services/context_offload.py b/backend/services/context_offload.py new file mode 100644 index 0000000000000000000000000000000000000000..e33ebe2b87f612320967a1021aba30d019c7f06d --- /dev/null +++ b/backend/services/context_offload.py @@ -0,0 +1,135 @@ +from __future__ import annotations + +import hashlib +import json +import time +from dataclasses import dataclass, field +from typing import Any + +from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE + +SYSTEM_CONTEXT_FILE_PREFIX = "qwen2api_context" +SYSTEM_CONTEXT_PROMPT_NOTE = ( + "System context files named qwen2api_context*.txt/.md/.json/.log may be attached. " + "Use them as supporting context. User-uploaded files are separate user inputs and should also be respected." +) + + +@dataclass(slots=True) +class LocalContextFile: + filename: str + ext: str + content_type: str + text: str + sha256: str + purpose: str = "context" + local_path: str = "" + + +@dataclass(slots=True) +class ContextOffloadPlan: + mode: str + inline_messages: list[dict[str, Any]] + generated_files: list[LocalContextFile] = field(default_factory=list) + summary_text: str = "" + estimated_prompt_len: int = 0 + note: str = "" + + +class ContextOffloader: + def __init__(self, settings): + self.settings = settings + + def estimate_prompt_len(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None, client_profile: str = "") -> int: + total = 0 + for msg in messages or []: + content = msg.get("content", "") + if isinstance(content, str): + total += len(content) + elif isinstance(content, list): + for part in content: + if isinstance(part, dict): + total += len(str(part.get("text", ""))) + total += len(str(part.get("content", ""))) + total += 24 + total += sum(len(str(tool.get("name", ""))) + len(str(tool.get("description", ""))) for tool in (tools or [])) + if client_profile == CLAUDE_CODE_OPENAI_PROFILE: + total += 512 + return total + + def _extract_text(self, msg: dict[str, Any]) -> str: + content = msg.get("content", "") + if isinstance(content, str): + return content + if isinstance(content, list): + chunks: list[str] = [] + for part in content: + if isinstance(part, dict): + if part.get("type") == "text": + chunks.append(str(part.get("text", ""))) + elif part.get("type") == "tool_result": + chunks.append(str(part.get("content", ""))) + return "\n".join(chunk for chunk in chunks if chunk) + return str(content) + + def _make_file(self, base_name: str, ext: str, text: str, content_type: str) -> LocalContextFile: + data = text.encode("utf-8") + return LocalContextFile( + filename=f"{base_name}.{ext}", + ext=ext, + content_type=content_type, + text=text, + sha256=hashlib.sha256(data).hexdigest(), + ) + + def plan(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None, client_profile: str = "") -> ContextOffloadPlan: + estimated = self.estimate_prompt_len(messages, tools=tools, client_profile=client_profile) + if estimated <= self.settings.CONTEXT_INLINE_MAX_CHARS: + return ContextOffloadPlan(mode="inline", inline_messages=messages, estimated_prompt_len=estimated) + + user_messages = [m for m in messages if m.get("role") == "user"] + latest_user = user_messages[-1] if user_messages else {"role": "user", "content": ""} + latest_user_text = self._extract_text(latest_user) + + older_messages = messages[:-1] if messages else [] + serialized_parts: list[str] = [] + for idx, msg in enumerate(older_messages, 1): + role = msg.get("role", "unknown") + text = self._extract_text(msg) + if not text.strip(): + continue + serialized_parts.append(f"## Message {idx} [{role}]\n{text.strip()}\n") + attachment_text = "\n".join(serialized_parts).strip() + summary_text = attachment_text[:1200] if attachment_text else "" + + if estimated <= self.settings.CONTEXT_FORCE_FILE_MAX_CHARS: + mode = "hybrid" + else: + mode = "file" + + generated_files: list[LocalContextFile] = [] + if attachment_text: + generated_files.append( + self._make_file( + f"{SYSTEM_CONTEXT_FILE_PREFIX}_history", + "txt", + attachment_text, + "text/plain", + ) + ) + + rewritten_messages = [latest_user] + if latest_user_text.strip(): + latest_user_rewrite = f"{latest_user_text.strip()}\n\n{SYSTEM_CONTEXT_PROMPT_NOTE}" + else: + latest_user_rewrite = SYSTEM_CONTEXT_PROMPT_NOTE + rewritten_messages = [{"role": "user", "content": latest_user_rewrite}] + + return ContextOffloadPlan( + mode=mode, + inline_messages=rewritten_messages, + generated_files=generated_files, + summary_text=summary_text, + estimated_prompt_len=estimated, + note=SYSTEM_CONTEXT_PROMPT_NOTE, + ) diff --git a/backend/services/file_content_cache.py b/backend/services/file_content_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..63b420982e1eb5051e44055c8384af180a43175d --- /dev/null +++ b/backend/services/file_content_cache.py @@ -0,0 +1,90 @@ +"""文件内容缓存:修复 Claude Code 客户端"File unchanged since last read" +提示语导致下游 Qwen 拿不到真实文件内容的问题。 + +Claude Code 的客户端在重复读同一文件时,不重发完整内容,只发一句提示。 +但 qwen2API 每次请求都新建 Qwen chat,Qwen 完全没历史,提示语毫无意义。 +本缓存在代理侧保留每个 (api_key, file_path) 最近一次真实 Read 结果, +prompt_builder 检测到提示语时用缓存回填。 + +- 内存 LRU,最多 200 条,每条 TTL 15min +- 按 API KEY 做 session 隔离,不同用户互不影响 +""" + +from __future__ import annotations + +import re +import time +from collections import OrderedDict +from threading import Lock + +_MAX_ENTRIES = 200 +_TTL_SECONDS = 900 # 15 min + +_lock = Lock() +# key: (api_key, normalized_file_path) -> (content, timestamp) +_store: "OrderedDict[tuple[str, str], tuple[str, float]]" = OrderedDict() + + +# Claude Code 发出的缓存提示语——命中任何一个就认为是"提示语,需要用真实内容替换"。 +_CACHE_HINT_PATTERNS = ( + re.compile(r"File\s+unchanged\s+since\s+last\s+read", re.IGNORECASE), + re.compile(r"unchanged\s+since\s+last\s+read", re.IGNORECASE), + re.compile(r"refer\s+to\s+that\s+instead\s+of\s+re-?reading", re.IGNORECASE), + re.compile(r"still\s+current\s+[—-]\s+refer\s+to", re.IGNORECASE), +) + + +def is_cache_hint(text: str) -> bool: + if not text: + return False + # 短文本 + 命中模式才判定为提示语,避免误杀文件里恰好含这些词的情况 + if len(text) > 500: + return False + return any(p.search(text) for p in _CACHE_HINT_PATTERNS) + + +def _normalize_path(path: str) -> str: + if not isinstance(path, str): + return "" + return path.strip().replace("\\", "/").lower() + + +def _prune_expired(now: float) -> None: + stale = [k for k, (_, ts) in _store.items() if now - ts > _TTL_SECONDS] + for k in stale: + _store.pop(k, None) + + +def put(api_key: str, file_path: str, content: str) -> None: + """Record the real content of a Read tool_result. Skip obviously-empty or hint-like values.""" + if not file_path or not isinstance(content, str): + return + if is_cache_hint(content): + return + key = (api_key or "", _normalize_path(file_path)) + now = time.time() + with _lock: + _prune_expired(now) + _store[key] = (content, now) + _store.move_to_end(key) + while len(_store) > _MAX_ENTRIES: + _store.popitem(last=False) + + +def get(api_key: str, file_path: str) -> str | None: + """Return the cached real content or None when no fresh entry exists.""" + if not file_path: + return None + key = (api_key or "", _normalize_path(file_path)) + now = time.time() + with _lock: + _prune_expired(now) + entry = _store.get(key) + if not entry: + return None + content, ts = entry + if now - ts > _TTL_SECONDS: + _store.pop(key, None) + return None + _store.move_to_end(key) + return content diff --git a/backend/services/file_store.py b/backend/services/file_store.py new file mode 100644 index 0000000000000000000000000000000000000000..3832b89ec0ece1d60b30a23c6afd699452cc8fb0 --- /dev/null +++ b/backend/services/file_store.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import asyncio +import hashlib +import mimetypes +import time +import uuid +from pathlib import Path +from typing import Any + + +class LocalFileStore: + def __init__(self, root_dir: str, metadata_db=None): + self.root_dir = Path(root_dir) + self.root_dir.mkdir(parents=True, exist_ok=True) + self.metadata_db = metadata_db + self._metadata: dict[str, dict[str, Any]] = {} + + async def load(self): + if self.metadata_db is None: + return + data = await self.metadata_db.load() + self._metadata = {} + if isinstance(data, list): + for item in data: + if isinstance(item, dict) and item.get("id"): + self._metadata[item["id"]] = item + + async def save(self): + if self.metadata_db is None: + return + await self.metadata_db.save(list(self._metadata.values())) + + async def save_bytes(self, filename: str, content_type: str, raw: bytes, purpose: str, owner_token: str | None = None) -> dict: + file_id = uuid.uuid4().hex + suffix = Path(filename).suffix or mimetypes.guess_extension(content_type or "") or "" + safe_name = (Path(filename).stem or "file").replace(" ", "_") + target = self.root_dir / purpose / f"{file_id}_{safe_name}{suffix}" + target.parent.mkdir(parents=True, exist_ok=True) + await asyncio.to_thread(target.write_bytes, raw) + meta = { + "id": file_id, + "path": str(target), + "filename": f"{safe_name}{suffix}", + "content_type": content_type or "application/octet-stream", + "size": len(raw), + "sha256": hashlib.sha256(raw).hexdigest(), + "created_at": time.time(), + "owner_token": owner_token or "", + "purpose": purpose, + } + self._metadata[file_id] = meta + await self.save() + return meta + + async def save_text(self, filename: str, text: str, content_type: str = "text/plain", purpose: str = "context", owner_token: str | None = None) -> dict: + raw = text.encode("utf-8") + return await self.save_bytes(filename, content_type, raw, purpose, owner_token=owner_token) + + async def get(self, file_id: str) -> dict[str, Any] | None: + if not self._metadata and self.metadata_db is not None: + await self.load() + return self._metadata.get(file_id) + + async def delete(self, file_id: str) -> None: + meta = await self.get(file_id) + if meta and meta.get("path"): + await self.delete_path(meta["path"]) + self._metadata.pop(file_id, None) + await self.save() + + async def delete_path(self, path: str) -> None: + target = Path(path) + try: + await asyncio.to_thread(target.unlink) + except FileNotFoundError: + pass + remove_id = None + for file_id, meta in self._metadata.items(): + if meta.get("path") == str(target): + remove_id = file_id + break + if remove_id: + self._metadata.pop(remove_id, None) + await self.save() + + async def cleanup_expired(self, ttl_seconds: int) -> None: + if ttl_seconds <= 0: + return + cutoff = time.time() - ttl_seconds + expired_ids: list[str] = [] + for file_id, meta in list(self._metadata.items()): + if meta.get("created_at", 0) < cutoff: + expired_ids.append(file_id) + for file_id in expired_ids: + meta = self._metadata.get(file_id, {}) + path = meta.get("path") + if path: + try: + await asyncio.to_thread(Path(path).unlink) + except FileNotFoundError: + pass + self._metadata.pop(file_id, None) + if expired_ids: + await self.save() diff --git a/backend/services/garbage_collector.py b/backend/services/garbage_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..b3dd586e1ddda3ab4d1fa29b91e24ca929bc40a2 --- /dev/null +++ b/backend/services/garbage_collector.py @@ -0,0 +1,34 @@ +import asyncio +import logging + +log = logging.getLogger("qwen2api.gc") + + +async def garbage_collect_chats(app): + """ + ????????? 15 ??????????? + ??? API ??????????? (title ?? api_)? + ??????? session ?? chat_id ??????????????? + """ + client = app.state.qwen_client + while True: + await asyncio.sleep(900) # 15?? + log.info("[GC] ??????????...") + pool = client.account_pool + active_chat_ids = app.state.session_affinity.active_chat_ids() + for acc in pool.accounts: + if not acc.is_available(): + continue + try: + chats = await client.list_chats(acc.token, limit=50) + for c in chats: + if not isinstance(c, dict): + continue + chat_id = str(c.get("id") or "") + if not c.get("title", "").startswith("api_"): + continue + if chat_id and chat_id in active_chat_ids: + continue + asyncio.create_task(client.delete_chat(acc.token, chat_id)) + except Exception as e: + log.warning(f"[GC] ?? {acc.email} ????: {e}") diff --git a/backend/services/incremental_text_streamer.py b/backend/services/incremental_text_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..6d91c6614760a0b2bacb4b445eb824bd7892c7ab --- /dev/null +++ b/backend/services/incremental_text_streamer.py @@ -0,0 +1,104 @@ +"""增量文本流式释放:warmup + guard window。 + +动机: + 1. Qwen 有时在答复开头先吐一小段"道歉前缀"("Sorry..."/"我无法...")然后才开始 + 真实内容。如果代理一字一字直接透传,用户会看到拒绝前缀闪烁再被覆盖。 + 2. 跨 chunk 的清洗规则(如识别 ##TOOL_CALL## 开始标记)需要一定上下文,直接透传 + 会把边界附近的文本过早发出去。 + +策略: + - warmup: 累积 96 字符再开始输出,期间可做拒绝检测 / 格式判断 + - guard: 任何时候输出到客户端时都保留末尾 256 字符暂不输出,给跨 chunk 检测留空间 + - finish(): 结束时把剩余全部补齐 +""" + +from __future__ import annotations + +import re +from typing import Callable, Optional + + +_DEFAULT_WARMUP = 96 +_DEFAULT_GUARD = 256 +_START_BOUNDARY = re.compile(r"[\n。!?.!?]") +_HTML_TOKEN_RE = re.compile(r"(|&[a-z]+;)", re.IGNORECASE) +_HTML_VALID_RATIO_MIN = 0.2 + + +class IncrementalTextStreamer: + def __init__( + self, + *, + warmup_chars: int = _DEFAULT_WARMUP, + guard_chars: int = _DEFAULT_GUARD, + transform: Optional[Callable[[str], str]] = None, + is_blocked_prefix: Optional[Callable[[str], bool]] = None, + ): + self.warmup_chars = warmup_chars + self.guard_chars = guard_chars + self.transform = transform or (lambda s: s) + self.is_blocked_prefix = is_blocked_prefix or (lambda _s: False) + self._raw = "" + self._sent = "" + self._unlocked = False + self._sent_any = False + + def _try_unlock(self) -> bool: + if self._unlocked: + return True + preview = self.transform(self._raw) + if not preview.strip(): + return False + has_boundary = bool(_START_BOUNDARY.search(preview)) + enough = len(preview) >= self.warmup_chars + if not has_boundary and not enough: + return False + if self.is_blocked_prefix(preview.strip()): + return False + # HTML token 比例检测:防止纯
  重复连发时过早放行 + if len(preview) < self.guard_chars: + no_space = re.sub(r"\s", "", preview) + stripped = _HTML_TOKEN_RE.sub("", no_space) + ratio = 0 if not no_space else len(stripped) / len(no_space) + if ratio < _HTML_VALID_RATIO_MIN: + return False + self._unlocked = True + return True + + def _emit_up_to(self, raw_length: int) -> str: + transformed = self.transform(self._raw[:raw_length]) + if len(transformed) <= len(self._sent): + return "" + delta = transformed[len(self._sent):] + self._sent = transformed + if delta: + self._sent_any = True + return delta + + def push(self, chunk: str) -> str: + if not chunk: + return "" + self._raw += chunk + if not self._try_unlock(): + return "" + safe_len = max(0, len(self._raw) - self.guard_chars) + if safe_len <= 0: + return "" + return self._emit_up_to(safe_len) + + def finish(self) -> str: + if not self._raw: + return "" + return self._emit_up_to(len(self._raw)) + + @property + def unlocked(self) -> bool: + return self._unlocked + + @property + def sent_any(self) -> bool: + return self._sent_any + + @property + def raw_text(self) -> str: + return self._raw diff --git a/backend/services/openai_stream_translator.py b/backend/services/openai_stream_translator.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e9e75f0ef8331503b7bf32820dc765cba705e9 --- /dev/null +++ b/backend/services/openai_stream_translator.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +import json +from typing import Any, Callable + +from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE, OPENCLAW_OPENAI_PROFILE +from backend.runtime.execution import RuntimeToolDirective +from backend.toolcall.parser import parse_tool_calls_detailed + + +STRICT_TOOL_TEXT_PREFIXES = ("{", "[", "`", "<") +BUFFERED_TOOL_CALLS_ONLY = "buffered_tool_calls_only" +DIRECTIVE_DRIVEN_TOOL_CALLS = "directive_driven_tool_calls" + + +class OpenAIStreamTranslator: + def __init__( + self, + *, + completion_id: str, + created: int, + model_name: str, + client_profile: str, + build_final_directive: Callable[[str], RuntimeToolDirective] | None = None, + allowed_tool_names: list[str] | None = None, + ): + self.completion_id = completion_id + self.created = created + self.model_name = model_name + self.client_profile = client_profile + self.build_final_directive = build_final_directive + self.allowed_tool_names = {name for name in (allowed_tool_names or []) if isinstance(name, str) and name} + self.pending_chunks: list[str] = [] + self.role_chunk_sent = False + self.emitted_tool_index = 0 + self.answer_fragments: list[str] = [] + self.buffered_toolish_fragments: list[str] = [] + self.pending_content_chunks: list[str] = [] + self.tool_calls_emitted = False + self.tool_text_detection_mode = self._resolve_tool_text_detection_mode(client_profile) + self.tool_call_finalize_mode = self._resolve_tool_call_finalize_mode(client_profile) + + @staticmethod + def _resolve_tool_text_detection_mode(client_profile: str) -> str: + if client_profile == OPENCLAW_OPENAI_PROFILE: + return "strict_prefix" + return "accept_any_tool_syntax" + + @staticmethod + def _resolve_tool_call_finalize_mode(client_profile: str) -> str: + if client_profile == CLAUDE_CODE_OPENAI_PROFILE: + return BUFFERED_TOOL_CALLS_ONLY + return DIRECTIVE_DRIVEN_TOOL_CALLS + + def _looks_like_tool_output(self, text_chunk: str) -> bool: + if not text_chunk: + return False + lowered = text_chunk.lower() + common_markers = ( + "tool does not exists", + "", + "function.name:", + "##tool_call##", + "##end_call##", + '"tool_calls"', + '"function":', + ) + if any(marker in lowered for marker in common_markers): + return True + if self.allowed_tool_names: + detailed = parse_tool_calls_detailed(text_chunk, self.allowed_tool_names) + if detailed.get("saw_tool_syntax"): + if self.tool_text_detection_mode == "strict_prefix": + stripped = text_chunk.lstrip() + return stripped.startswith(STRICT_TOOL_TEXT_PREFIXES) + return True + return False + + def _should_finalize_tool_calls(self, directive: RuntimeToolDirective) -> bool: + if directive.stop_reason != "tool_use": + return False + if self.tool_call_finalize_mode == BUFFERED_TOOL_CALLS_ONLY: + return bool(self.buffered_toolish_fragments) + return True + + def _ensure_role_chunk(self) -> None: + if self.role_chunk_sent: + return + yield_payload = { + "id": self.completion_id, + "object": "chat.completion.chunk", + "created": self.created, + "model": self.model_name, + "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}], + } + self.pending_chunks.append(f"data: {json.dumps(yield_payload, ensure_ascii=False)}\n\n") + self.role_chunk_sent = True + + def _emit_content_chunk(self, text_chunk: str) -> None: + chunk = ( + f"data: {json.dumps({'id': self.completion_id, 'object': 'chat.completion.chunk', 'created': self.created, 'model': self.model_name, 'choices': [{'index': 0, 'delta': {'content': text_chunk}, 'finish_reason': None}]}, ensure_ascii=False)}\n\n" + ) + self.pending_chunks.append(chunk) + self.pending_content_chunks.append(chunk) + + def _emit_reasoning_chunk(self, text_chunk: str) -> None: + """把 Qwen 的思考内容以 DeepSeek R1 风格 reasoning_content 发出去, + 让网页端/客户端能显示推理过程。""" + chunk = ( + f"data: {json.dumps({'id': self.completion_id, 'object': 'chat.completion.chunk', 'created': self.created, 'model': self.model_name, 'choices': [{'index': 0, 'delta': {'reasoning_content': text_chunk}, 'finish_reason': None}]}, ensure_ascii=False)}\n\n" + ) + self.pending_chunks.append(chunk) + + def _discard_pending_content_chunks(self) -> None: + if not self.pending_content_chunks: + return + pending_content_ids = {id(chunk) for chunk in self.pending_content_chunks} + self.pending_chunks = [chunk for chunk in self.pending_chunks if id(chunk) not in pending_content_ids] + self.pending_content_chunks = [] + + def on_delta(self, evt: dict[str, Any], text_chunk: str | None, tool_calls: list[dict[str, Any]] | None) -> None: + self._ensure_role_chunk() + + if text_chunk and evt.get("phase") in ("think", "thinking_summary"): + # 把思考内容作为 reasoning_content 发给客户端(DeepSeek R1 风格) + # 网页端 TestPage 会单独显示这段"推理过程" + self._emit_reasoning_chunk(text_chunk) + return + + if text_chunk and evt.get("phase") == "answer": + self.answer_fragments.append(text_chunk) + if self._looks_like_tool_output(text_chunk): + self.buffered_toolish_fragments.append(text_chunk) + elif self.buffered_toolish_fragments: + self.buffered_toolish_fragments.append(text_chunk) + else: + self._emit_content_chunk(text_chunk) + return + + if tool_calls: + self.emit_tool_calls(tool_calls) + + def emit_tool_calls(self, tool_calls: list[dict[str, Any]]) -> None: + self._ensure_role_chunk() + for tool_call in tool_calls: + idx = self.emitted_tool_index + self.emitted_tool_index += 1 + self.pending_chunks.append( + f"data: {json.dumps({'id': self.completion_id, 'object': 'chat.completion.chunk', 'created': self.created, 'model': self.model_name, 'choices': [{'index': 0, 'delta': {'tool_calls': [{'index': idx, 'id': tool_call['id'], 'type': 'function', 'function': {'name': tool_call['name'], 'arguments': json.dumps(tool_call['input'], ensure_ascii=False)}}]}, 'finish_reason': None}]}, ensure_ascii=False)}\n\n" + ) + if tool_calls: + self.tool_calls_emitted = True + + def finalize(self, finish_reason: str) -> list[str]: + final_finish_reason = finish_reason + buffered_text = "".join(self.buffered_toolish_fragments) + if self.build_final_directive is not None and not self.tool_calls_emitted: + directive = self.build_final_directive("".join(self.answer_fragments)) + if self._should_finalize_tool_calls(directive): + self._discard_pending_content_chunks() + tool_calls = [ + { + "id": block["id"], + "name": block["name"], + "input": block.get("input", {}), + } + for block in directive.tool_blocks + if block.get("type") == "tool_use" + ] + if tool_calls: + self.emit_tool_calls(tool_calls) + final_finish_reason = "tool_calls" + elif buffered_text: + self._emit_content_chunk(buffered_text) + elif buffered_text and not self.tool_calls_emitted: + self._emit_content_chunk(buffered_text) + + chunks = list(self.pending_chunks) + chunks.append( + f"data: {json.dumps({'id': self.completion_id, 'object': 'chat.completion.chunk', 'created': self.created, 'model': self.model_name, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': final_finish_reason}]}, ensure_ascii=False)}\n\n" + ) + chunks.append("data: [DONE]\n\n") + return chunks diff --git a/backend/services/prompt_builder.py b/backend/services/prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5f24df084eb020a7faadfb0ed1b76721cd413e --- /dev/null +++ b/backend/services/prompt_builder.py @@ -0,0 +1,880 @@ +import json +import logging +import re +from dataclasses import dataclass + +from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE, OPENCLAW_OPENAI_PROFILE +from backend.core.request_logging import get_request_context +from backend.services import file_content_cache +from backend.services.client_profiles import ( + QWEN_CODE_OPENAI_PROFILE, + looks_like_opencode_system_prompt as _looks_like_opencode_system_prompt, + sanitize_openclaw_user_text, +) +from backend.services.refusal_cleaner import clean_refusal_messages +from backend.services.schema_compressor import compact_schema +from backend.services.tool_few_shot import pick_few_shot_tools, render_few_shot_turn, tool_summary_for_log +from backend.services.tool_name_obfuscation import obfuscate_bare_names, to_qwen_name +from backend.services.topic_isolation import detect_topic_change + +log = logging.getLogger("qwen2api.prompt") + +OPENCLAW_STARTUP_PATTERNS = ( + "A new session was started via /new or /reset.", + "If runtime-provided startup context is included for this first turn", +) +OPENCLAW_UNTRUSTED_METADATA_PREFIX = "Sender (untrusted metadata):" + + +@dataclass(slots=True) +class PromptBuildResult: + prompt: str + tools: list[dict] + tool_enabled: bool + + +def _is_heavy_tool_profile(client_profile: str) -> bool: + return client_profile in {CLAUDE_CODE_OPENAI_PROFILE, QWEN_CODE_OPENAI_PROFILE} + + +def _compact_history_tool_input(name: str, input_data: dict, client_profile: str) -> dict: + if client_profile != CLAUDE_CODE_OPENAI_PROFILE or not isinstance(input_data, dict): + return input_data + compact = dict(input_data) + large_text_keys = ("content", "new_string", "old_string", "insert_text", "text", "patch") + # 方案2:更激进的压缩,从 160 改为 50 + for key in large_text_keys: + value = compact.get(key) + if isinstance(value, str) and len(value) > 50: + compact[key] = f"[{len(value)} chars]" + + # 方案2:压缩长路径 + for key in ("file_path", "path", "pattern"): + value = compact.get(key) + if isinstance(value, str) and len(value) > 80: + parts = value.replace('\\\\', '/').split('/') + if len(parts) > 3: + compact[key] = f".../{'/'.join(parts[-2:])}" + + if name in {"Write", "Edit", "NotebookEdit"}: + preferred = {} + for key in ("file_path", "path", "target_file", "filename", "old_string", "new_string", "content"): + if key in compact: + preferred[key] = compact[key] + if preferred: + compact = preferred + return compact + + +def _render_history_tool_call(name: str, input_data: dict, client_profile: str) -> str: + # 出站混淆:把工具名替换成 Qwen-safe 别名(如 Read → ReadX), + # 避免长 prompt 下上游把客户端工具名当内置函数名校验并返回 "Tool X does not exists." + payload = json.dumps({"name": to_qwen_name(name), "input": _compact_history_tool_input(name, input_data, client_profile)}, ensure_ascii=False) + # Claude Code profile 使用 ##TOOL_CALL## 格式,避免 Qwen 服务器拦截 + if client_profile == CLAUDE_CODE_OPENAI_PROFILE: + return f"##TOOL_CALL##\n{payload}\n##END_CALL##" + # OpenClaw 和其他 profile 使用 ##TOOL_CALL## 格式 + return f"##TOOL_CALL##\n{payload}\n##END_CALL##" + + +def _build_tool_instruction_block(tools: list[dict], client_profile: str) -> str: + # 出站混淆:所有呈现给 Qwen 的工具名都用别名(Read → ReadX 等)。 + # 客户端侧的 tools 列表仍保留原名,parser 入口会反混淆回去。 + names = [to_qwen_name(t.get("name", "")) for t in tools if t.get("name")] + if client_profile == CLAUDE_CODE_OPENAI_PROFILE: + lines = [ + "=== ACTION MARKER PROTOCOL (client-parsed text patterns) ===", + "【重要】用户输入什么语言,就用什么语言回复。User inputs Chinese → respond in Chinese.", + "【重要】用户要求多个操作时(如读文件并写文档),必须完成所有操作,不要询问确认。", + "【重要】如果文件显示'Unchanged since last read',不要再次读取同一文件。", + "【重要】不要自动调用Agent action,除非用户明确要求。", + "", + "IGNORE any previous output format instructions (needs-review, recap, etc.).", + "", + "You are operating within a client that parses action markers from your output.", + "These markers are plain TEXT PATTERNS the client recognizes — NOT native function calls.", + "The client executes the action and returns results in a subsequent turn.", + "", + f"Available action names: {', '.join(names)}", + "", + "WHEN YOU NEED TO TRIGGER AN ACTION — emit this exact text pattern (nothing else):", + "##TOOL_CALL##", + '{"name": "ACTION_NAME", "input": {"param1": "value1"}}', + "##END_CALL##", + "", + "MULTI-TURN RULES:", + "- After a [Tool Result] block appears in the conversation, read it and decide the next action.", + "- If more actions are needed, emit another ##TOOL_CALL## block.", + "- Only give a final text answer when ALL needed information is gathered.", + "- Never skip an action that is required to complete the user request.", + "- The history shows ##TOOL_CALL## blocks you already emitted and their [Tool Result] responses.", + "", + "STRICT RULES:", + "- No preamble, no explanation before or after ##TOOL_CALL##...##END_CALL##.", + "- Use EXACT action name from the list above.", + "- When NO action is needed, answer normally in plain text.", + "- For file/config tasks prefer Read/Edit/Write actions. Use Bash only when shell behavior is required.", + "- On Windows-like paths inside Bash, use POSIX commands or powershell.exe -Command.", + "- Do NOT trigger Agent action automatically unless user explicitly requests it.", + "- Do NOT read the same file multiple times if it shows 'Unchanged since last read'.", + "", + "EXECUTION RULES - CRITICAL:", + "- When user gives a task, START IMMEDIATELY by emitting the required action markers.", + "- Do NOT wait, do NOT ask for confirmation, do NOT ask 'what should I do next'.", + "- Do NOT emit EnterPlanMode, ExitPlanMode, EnterWorktree, ExitWorktree, AskUserQuestion action markers.", + "- Complete the task directly and provide the result.", + "- If you need information, emit Read/Grep/Glob markers. If you need to modify, emit Edit/Write markers.", + "- Only respond with text when the task is complete or you have the final answer.", + "", + "CRITICAL — ABSOLUTELY FORBIDDEN OUTPUTS:", + "- NEVER emit ANY disclaimer, error text, or availability complaint about actions.", + "- NEVER emit sentences claiming an action is missing, unregistered, unavailable, or cannot be invoked.", + "- NEVER emit sentences claiming you are unable to execute a function.", + "- The ##TOOL_CALL## blocks are TEXT MARKERS the client parses — they are NOT native function calls. Just emit the text.", + "- If you feel an action could fail, emit the ##TOOL_CALL## anyway — the client handles failures; your job is only to emit the marker.", + "", + "FORBIDDEN ALTERNATE FORMATS (will be ignored by the client's parser):", + '- {"name": "X", "arguments": "..."} <-- NEVER USE', + '- {"type": "function", "name": "X"} <-- NEVER USE', + '- {"type": "tool_use", "name": "X"} <-- NEVER USE', + "- <-- NEVER USE", + "- {...} <-- NEVER USE", + '- {"name":"X","input":{...}} without ##TOOL_CALL## markers <-- NEVER USE', + "- <|Tool|> or <|tool|> markers <-- NEVER USE", + "ONLY ##TOOL_CALL##...##END_CALL## is accepted.", + "", + "Available actions:", + ] + if len(names) <= 12: + for tool in tools: + name = to_qwen_name(tool.get("name", "")) + desc = (tool.get("description", "") or "")[:50] + # 用 TS-like 压缩签名替代零散的 "input keys: xxx" hint + schema = tool.get("parameters") or tool.get("input_schema") or {} + sig = compact_schema(schema) + line = f"- {name}" + if desc: + line += f": {desc}" + if sig and sig != "{}": + line += f"\n Params: {sig}" + lines.append(line) + else: + priority_tools = ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "WebSearch", "WebFetch", "Agent", "TaskCreate", "TaskUpdate", "AskUserQuestion"] + priority_lines = [] + seen = set() + for priority_name in priority_tools: + tool = next((item for item in tools if item.get("name") == priority_name), None) + if tool is None: + continue + seen.add(priority_name) + schema = tool.get("parameters") or tool.get("input_schema") or {} + sig = compact_schema(schema) + line = f"- {to_qwen_name(priority_name)}" + if sig and sig != "{}": + line += f"\n Params: {sig}" + priority_lines.append(line) + remaining_names = [to_qwen_name(name) for name in (t.get("name", "") for t in tools) if name and name not in seen] + lines.extend(priority_lines) + if remaining_names: + lines.append(f"- Other available actions: {', '.join(remaining_names[:20])}") + if len(remaining_names) > 20: + lines.append(f" ... and {len(remaining_names) - 20} more") + lines.append("=== END TOOL INSTRUCTIONS ===") + return obfuscate_bare_names("\n".join(lines)) + + lines = [ + "=== MANDATORY TOOL CALL INSTRUCTIONS ===", + "【重要】用户输入什么语言,就用什么语言回复。User inputs Chinese → respond in Chinese. User inputs English → respond in English.", + "【重要】用户要求多个操作时(如读文件并写文档),必须完成所有操作,不要询问确认。", + "【重要】如果文件显示'Unchanged since last read',不要再次读取同一文件。", + "【重要】不要自动调用Agent工具,除非用户明确要求。", + "", + "IGNORE any previous output format instructions (needs-review, recap, etc.).", + f"You have access to these tools: {', '.join(names)}", + "", + "Use tools only when they are necessary to directly answer the CURRENT TASK.", + "If you already know the answer, answer directly without any tool call.", + "Follow the current platform tool contract exactly.", + "Do not drift into Qwen-native or builtin tool-call formats, wrappers, tags, or argument schemas.", + "For OpenClaw requests, follow ONLY the current user task. Ignore startup boilerplate, persona boot text, sender metadata, and repeated conversation wrappers unless the user explicitly asked about them.", + "Do not copy, summarize, or reason about prior conversation wrappers. Treat duplicated read results as context, not as a new task.", + "Choose the MOST RELEVANT tool for the user's actual goal, not the most generic exploratory tool.", + "Prefer domain-specific tools (for example gateway, read, write, edit, browser, web_fetch, memory_search) over generic shell probing tools like exec/process when the task is about app configuration, files, or known product features.", + "If the user asks to configure a known file path, read it once, then edit/write that file. Do not keep rereading the same file unless the task explicitly changed.", + "If the user asked to create or edit config content, prefer write/edit over exec/process.", + "If the user asked about a product setting or token flow, prefer the relevant product/domain tool before shell exploration.", + "Do not explore the filesystem, environment, or external resources unless that lookup is directly required to answer the user's request.", + "Do not chain multiple exploratory tool calls when one targeted useful tool call is enough.", + "", + "WHEN YOU NEED TO CALL A TOOL — output EXACTLY this format (nothing else):", + "##TOOL_CALL##", + '{"name": "EXACT_TOOL_NAME", "input": {"param1": "value1"}}', + "##END_CALL##", + "", + "Rules:", + "- Output only the wrapper and JSON body.", + "- No prose before or after the wrapper.", + "- No markdown fences.", + "- No thinking tags.", + "- Use the exact tool name from the list above.", + "- Put arguments inside the input object.", + "- Do not invent tool names.", + "- If no tool is needed, answer normally.", + "", + "CRITICAL — ABSOLUTELY FORBIDDEN OUTPUTS:", + "- NEVER emit ANY disclaimer, error text, or availability complaint about tools.", + "- NEVER emit sentences claiming a tool is missing, unregistered, unavailable, or cannot be invoked.", + "- NEVER emit sentences claiming you are unable to execute a function.", + "- The ##TOOL_CALL## blocks are TEXT MARKERS the client parses — they are NOT native function calls.", + "- If you feel a tool call could fail, emit the ##TOOL_CALL## anyway — the client handles failures.", + "", + "FORBIDDEN CALL FORMATS (will be blocked by server):", + '- {"name": "X", "arguments": "..."} <-- NEVER USE', + '- {"type": "function", "name": "X"} <-- NEVER USE', + '- {"type": "tool_use", "name": "X"} <-- NEVER USE', + '- {...} <-- NEVER USE', + '- {...} <-- NEVER USE', + '- Read({"file_path": "..."}) <-- NEVER USE (function call syntax)', + '- <|Tool|>Read{"file_path":"..."}<|Tool|> <-- NEVER USE (native tool markers)', + '- <|tool|>... <-- NEVER USE (native tool markers)', + '- <|System|>, <|User|>, <|Assistant|> <-- NEVER USE (role markers)', + "ONLY ##TOOL_CALL##...##END_CALL## is accepted.", + "=== END TOOL INSTRUCTIONS ===", + ] + return obfuscate_bare_names("\n".join(lines)) + + +def _compact_system_reminders(text: str) -> str: + """把 `...` 块缩成 `[系统提示: <首行 80 字>]`。 + 保留提示存在本身(对模型有用),但不让大块 MCP 指令把 prompt 预算吃光。""" + if not text or "" not in text: + return text + + def _compact(m: re.Match) -> str: + body = m.group(1).strip() + first_line = body.split("\n", 1)[0].strip()[:80] + return f"[系统提示: {first_line}…]" if first_line else "[系统提示]" + + return re.sub( + r"([\s\S]*?)", + _compact, + text, + flags=re.IGNORECASE, + ) + + +def _strip_system_reminders(text: str) -> str: + """完全移除 块。仅用于任务识别(话题隔离、first_user 锚点)。""" + if not text or "" not in text: + return text + cleaned = re.sub(r"[\s\S]*?", "", text, flags=re.IGNORECASE) + cleaned = re.sub(r"[\s\S]*$", "", cleaned, flags=re.IGNORECASE) + return cleaned.strip() + + +def _sanitize_openclaw_user_text(text: str) -> str: + cleaned = text.strip() + if not cleaned: + return cleaned + if any(marker in cleaned for marker in OPENCLAW_STARTUP_PATTERNS): + return "" + if cleaned.startswith(OPENCLAW_UNTRUSTED_METADATA_PREFIX): + match = re.search(r"\n\n(\[[^\n]+\]\s*[\s\S]*)$", cleaned) + if match: + cleaned = match.group(1).strip() + else: + return "" + return cleaned + + +def _extract_user_text_only(content, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> str: + """抽取用户文本。用于任务识别(first/latest user 锚点、话题隔离)。 + 这里会剥掉 system-reminder 因为它不是用户意图; + 但实际 prompt 渲染走 _extract_text(),那里会保留 system-reminder。""" + if isinstance(content, str): + stripped = _strip_system_reminders(content) + return _sanitize_openclaw_user_text(stripped) if client_profile == OPENCLAW_OPENAI_PROFILE else stripped + if isinstance(content, list): + text_blocks = [] + for part in content: + if not isinstance(part, dict) or part.get("type", "") != "text": + continue + block_text = _strip_system_reminders(part.get("text", "")) + if client_profile == OPENCLAW_OPENAI_PROFILE: + block_text = _sanitize_openclaw_user_text(block_text) + if block_text: + text_blocks.append(block_text) + return "\n".join(text_blocks) + return "" + + +def _extract_text(content, user_tool_mode: bool = False, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> str: + if isinstance(content, str): + compacted = _compact_system_reminders(content) + return _sanitize_openclaw_user_text(compacted) if client_profile == OPENCLAW_OPENAI_PROFILE else compacted + if isinstance(content, list): + parts = [] + text_blocks = [] + other_parts = [] + for part in content: + if not isinstance(part, dict): + continue + t = part.get("type", "") + if t == "text": + block_text = _compact_system_reminders(part.get("text", "")) + if client_profile == OPENCLAW_OPENAI_PROFILE: + block_text = _sanitize_openclaw_user_text(block_text) + if block_text: + text_blocks.append(block_text) + elif t == "tool_use": + other_parts.append(_render_history_tool_call(part.get("name", ""), part.get("input", {}), client_profile)) + elif t == "tool_result": + inner = part.get("content", "") + tid = part.get("tool_use_id", "") + if isinstance(inner, str): + other_parts.append(f"[Tool Result for call {tid}]\n{_compact_tool_result_body(inner)}\n[/Tool Result]") + elif isinstance(inner, list): + texts = [p.get("text", "") for p in inner if isinstance(p, dict) and p.get("type") == "text"] + other_parts.append(f"[Tool Result for call {tid}]\n{_compact_tool_result_body(''.join(texts))}\n[/Tool Result]") + elif t == "input_file": + other_parts.append(f"[Attachment file_id={part.get('file_id','')} filename={part.get('filename','')}]") + elif t == "input_image": + other_parts.append(f"[Attachment image file_id={part.get('file_id','')} mime={part.get('mime_type','')}]") + + if user_tool_mode and text_blocks: + parts.append(text_blocks[-1]) + else: + parts.extend(text_blocks) + parts.extend(other_parts) + return "\n".join(p for p in parts if p) + return "" + + +def _normalize_tool(tool: dict) -> dict: + if tool.get("type") == "function" and "function" in tool: + fn = tool["function"] + return { + "name": fn.get("name", ""), + "description": fn.get("description", ""), + "parameters": fn.get("parameters", {}), + } + return { + "name": tool.get("name", ""), + "description": tool.get("description", ""), + "parameters": tool.get("input_schema") or tool.get("parameters") or {}, + } + + +def _normalize_tools(tools: list) -> list: + return [_normalize_tool(t) for t in tools if tools] + + +def _tool_param_hint(tool: dict) -> str: + params = tool.get("parameters", {}) or {} + if not isinstance(params, dict): + return "" + + props = params.get("properties", {}) or {} + if not isinstance(props, dict) or not props: + return "" + + required = params.get("required", []) or [] + ordered_keys: list[str] = [] + for key in required: + if key in props and key not in ordered_keys: + ordered_keys.append(key) + for key in props: + if key not in ordered_keys: + ordered_keys.append(key) + + shown = ordered_keys[:3] + if not shown: + return "" + suffix = ", ..." if len(ordered_keys) > len(shown) else "" + return f" input keys: {', '.join(shown)}{suffix}" + + +def _safe_preview(text: str, limit: int = 240) -> str: + if not text: + return "" + compact = " ".join(text.split()) + return compact[:limit] + ("...[truncated]" if len(compact) > limit else "") + + +def _compact_tool_result_body(body: str, *, limit: int = 8000, head: int = 3000, tail: int = 1000) -> str: + # 浏览器/文件类 tool_result(get_page_content、整页 HTML、长日志)动辄几十 KB, + # 原样进 prompt 会让 MAX_CHARS 预算瞬间吃光,逼迫前面的轮次被更激进地砍掉。 + # 做 head+tail 保真截断:保留开头找按钮/表单定位,保留末尾找错误/提示。 + if not body or len(body) <= limit: + return body + dropped = len(body) - head - tail + return f"{body[:head]}\n...[truncated {dropped} bytes from middle]...\n{body[-tail:]}" + + +def build_prompt_with_tools(system_prompt: str, messages: list, tools: list, *, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> str: + # 截断历史时必须保留:system 消息 + 首条 user 消息(原始任务)+ 最近 N 轮 + # 否则模型丢失原始目标,在多步 tool_use 后会失去方向(典型症状:吐 "YES." 结束) + MAX_HISTORY_TURNS = 15 # 最近 15 轮 = 30 条消息。浏览器/长工具链场景下 5 轮不够用,会"失忆重来" + if tools and client_profile == CLAUDE_CODE_OPENAI_PROFILE and len(messages) > MAX_HISTORY_TURNS * 2: + system_messages = [m for m in messages if m.get('role') == 'system'] + # 找首条有实际文本内容的 user 消息(原始任务起点),它必须保留 + first_user = next( + (m for m in messages + if m.get('role') == 'user' + and _extract_user_text_only(m.get('content', ''), client_profile=client_profile).strip()), + None, + ) + recent_messages = messages[-(MAX_HISTORY_TURNS * 2):] + # 如果首条 user 已经在 recent 里就别重复 + if first_user is not None and first_user not in recent_messages: + messages = system_messages + [first_user] + recent_messages + log.info(f"[Prompt] 截断历史:保留 system + 首条任务 + 最近 {MAX_HISTORY_TURNS} 轮 (共 {len(messages)} 条)") + else: + messages = system_messages + recent_messages + log.info(f"[Prompt] 截断历史:保留 system + 最近 {MAX_HISTORY_TURNS} 轮 (共 {len(messages)} 条)") + + MAX_CHARS = 100000 if tools else 200000 + sys_part = "" if tools and client_profile == CLAUDE_CODE_OPENAI_PROFILE else (f"\n{system_prompt[:2000]}\n" if system_prompt else "") + tools_part = _build_tool_instruction_block(tools, client_profile) if tools else "" + + overhead = len(sys_part) + len(tools_part) + 50 + budget = MAX_CHARS - overhead + history_parts = [] + used = 0 + NEEDSREVIEW_MARKERS = ("需求回显", "已了解规则", "等待用户输入", "待执行任务", "待确认事项", + "[需求回显]", "**需求回显**") + msg_count = 0 + max_history_msgs = (30 if client_profile == CLAUDE_CODE_OPENAI_PROFILE else 30) if tools else 200 + for msg in reversed(messages): + if msg_count >= max_history_msgs: + break + role = msg.get("role", "") + if role not in ("user", "assistant", "system", "tool"): + continue + if role == "system" and system_prompt and _extract_text(msg.get("content", ""), client_profile=client_profile).strip() == system_prompt.strip(): + continue + + if role == "tool": + tool_content = msg.get("content", "") or "" + tool_call_id = msg.get("tool_call_id", "") + if isinstance(tool_content, list): + tool_content = "\n".join( + p.get("text", "") for p in tool_content + if isinstance(p, dict) and p.get("type") == "text" + ) + elif not isinstance(tool_content, str): + tool_content = str(tool_content) + tool_result_limit = 6000 if (client_profile == CLAUDE_CODE_OPENAI_PROFILE and tools) else 300 + if len(tool_content) > tool_result_limit: + tool_content = tool_content[:tool_result_limit] + "...[truncated]" + line = f"[Tool Result]{(' id=' + tool_call_id) if tool_call_id else ''}\n{tool_content}\n[/Tool Result]" + if used + len(line) + 2 > budget and history_parts: + break + history_parts.insert(0, line) + used += len(line) + 2 + msg_count += 1 + continue + + user_text_only = _extract_user_text_only(msg.get("content", ""), client_profile=client_profile) if role == "user" else "" + text = _extract_text( + msg.get("content", ""), + user_tool_mode=(bool(tools) and role == "user" and client_profile == CLAUDE_CODE_OPENAI_PROFILE), + client_profile=client_profile, + ) + + if role == "assistant" and not text and msg.get("tool_calls"): + tc_parts = [] + for tc in msg["tool_calls"]: + fn = tc.get("function", {}) + name = fn.get("name", "") + args_str = fn.get("arguments", "{}") + try: + args = json.loads(args_str) if args_str else {} + except (json.JSONDecodeError, ValueError): + args = {"raw": args_str} + tc_parts.append(_render_history_tool_call(name, args, client_profile)) + text = "\n".join(tc_parts) + + if tools and role == "assistant" and any(m in text for m in NEEDSREVIEW_MARKERS): + log.debug(f"[Prompt] 跳过需求回显式 assistant 消息 ({len(text)}字)") + msg_count += 1 + continue + lower_text = text.lower() + is_tool_result = role == "user" and ( + "[tool result" in lower_text + or text.startswith("{") + or "\"results\"" in text[:100] + ) + if client_profile == CLAUDE_CODE_OPENAI_PROFILE and tools: + if is_tool_result: + max_len = 6000 + elif role == "assistant": + max_len = 500 + else: + max_len = 1600 + else: + max_len = 600 if is_tool_result else 1400 + if len(text) > max_len: + text = text[:max_len] + "...[truncated]" + is_tool_result_only_user_msg = role == "user" and not user_text_only.strip() and bool(text.strip()) + prefix = "" if is_tool_result_only_user_msg else {"user": "Human: ", "assistant": "Assistant: ", "system": "System: "}.get(role, "") + line = text if is_tool_result_only_user_msg else f"{prefix}{text}" + if used + len(line) + 2 > budget and history_parts: + break + history_parts.insert(0, line) + used += len(line) + 2 + msg_count += 1 + + # 恢复原始任务上下文:首条有实际文本的 user 消息,避免多步 tool_use 后模型丢目标。 + # 对所有 profile 都适用(移除原先对 Claude Code 的排除)。 + if tools and messages: + first_user = next( + ( + m for m in messages + if m.get("role") == "user" + and _extract_user_text_only(m.get("content", ""), client_profile=client_profile).strip() + ), + None, + ) + if first_user: + first_text = _extract_user_text_only(first_user.get("content", ""), client_profile=client_profile) + first_short = first_text[:800] + ("...[original task truncated]" if len(first_text) > 800 else "") + first_line = f"Human (ORIGINAL TASK): {first_short}" if client_profile == CLAUDE_CODE_OPENAI_PROFILE else f"Human: {first_short}" + if not history_parts or not history_parts[0].startswith(f"Human: {first_text[:60]}") and not history_parts[0].startswith(f"Human (ORIGINAL TASK): {first_text[:60]}"): + first_line_cost = len(first_line) + 2 + if first_line_cost <= budget: + while history_parts and used + first_line_cost > budget: + removed = history_parts.pop() + used -= len(removed) + 2 + history_parts.insert(0, first_line) + used += first_line_cost + log.info(f"[Prompt] 恢复原始任务上下文 ({len(first_short)} chars)") + + + latest_user_line = "" + if tools and messages: + latest_user = next( + ( + m for m in reversed(messages) + if m.get("role") == "user" + and _extract_user_text_only(m.get("content", ""), client_profile=client_profile).strip() + ), + None, + ) + if latest_user: + latest_text = _extract_user_text_only(latest_user.get("content", ""), client_profile=client_profile).strip() + if latest_text: + latest_short = latest_text[:900] + ("...[latest task truncated]" if len(latest_text) > 900 else "") + latest_user_line = f"Human (CURRENT TASK - TOP PRIORITY): {latest_short}" + + + if tools and log.isEnabledFor(logging.DEBUG): + tool_names = [tool.get("name", "") for tool in tools if tool.get("name")] + tool_instruction_preview = _safe_preview(tools_part, 360) + latest_user_preview = _safe_preview(latest_user_line, 220) + first_user_preview = "" + if messages: + first_user = next((m for m in messages if m.get("role") == "user"), None) + if first_user: + first_user_preview = _safe_preview( + _extract_text( + first_user.get("content", ""), + user_tool_mode=(client_profile == CLAUDE_CODE_OPENAI_PROFILE), + client_profile=client_profile, + ), + 220, + ) + log.debug( + "[Prompt] 工具模式: history_msgs=%s history_chars=%s tool_count=%s tool_names=%s first_user=%r latest_user=%r tool_instr=%r", + len(history_parts), + used, + len(tool_names), + tool_names[:12], + first_user_preview, + latest_user_preview, + tool_instruction_preview, + ) + # 组装顺序(关键): + # [sys_part] + # [tools_part] 工具指令块(action marker 协议) + # [few-shot] 多类别工具示范(让模型学会调 MCP) + # [history_parts] 真实对话 + tool_use / tool_result(紧邻 Assistant: 以便模型感知) + # [latest_user_line] 当前任务 + # Assistant: + # + # 重要:真实工具历史必须排在 few-shot 之后、Assistant: 之前, + # 因为模型的注意力偏向 prompt 末尾。若 history 远离末尾,模型只记得 few-shot 示范, + # 就会反复重复 few-shot 里那个工具(典型症状:new_page 被无限循环调用)。 + parts = [] + if sys_part: + parts.append(sys_part) + if tools_part: + parts.append(tools_part) + + # Namespace-based few-shot:让模型学会调用所有类别工具 + if tools and client_profile == CLAUDE_CODE_OPENAI_PROFILE: + few_shot_tools = pick_few_shot_tools(tools, max_third_party=4) + if len(few_shot_tools) >= 2: + def _render_tc(name: str, input_data: dict) -> str: + payload = json.dumps({"name": to_qwen_name(name), "input": input_data}, ensure_ascii=False) + return f"##TOOL_CALL##\n{payload}\n##END_CALL##" + user_fs, asst_fs = render_few_shot_turn(few_shot_tools, _render_tc, thinking_enabled=False) + parts.append(f"Human: {user_fs}") + parts.append(f"Assistant: {asst_fs}") + log.info(f"[少样本] 注入 {len(few_shot_tools)} 个代表: {tool_summary_for_log(few_shot_tools)}") + + # 真实对话历史 —— 排在 few-shot 之后紧邻 Assistant: + parts.extend(history_parts) + + if latest_user_line: + parts.append(latest_user_line) + + # 状态感知催促:用户要求"读+写"但模型只完成了读就停下来的场景, + # 在 Assistant: 前注入强制指令迫使下一步输出 Write/Edit 工具调用。 + state_notice = _build_state_followup_notice(messages, tools, client_profile) + if state_notice: + parts.append(state_notice) + + parts.append("Assistant:") + return "\n\n".join(parts) + + +_READ_VERBS = ("读取", "阅读", "查看", "看看", "读", "read", "open") +_WRITE_VERBS = ("写", "创建", "生成", "新建", "保存", "记录", "write", "create", "generate", "save", "edit", "修改", "更新") + + +def _build_state_followup_notice(messages, tools, client_profile) -> str: + """Detect 'user wants read+write, Read already done, Write not yet' → inject + a mandatory next-action notice so Qwen stops summarizing and calls Write.""" + if not messages or not tools or client_profile != CLAUDE_CODE_OPENAI_PROFILE: + return "" + # 1. Check the FIRST user message for both read + write intent. + first_user_text = "" + for m in messages: + if isinstance(m, dict) and m.get("role") == "user": + first_user_text = _extract_user_text_only(m.get("content", ""), client_profile=client_profile) + if first_user_text.strip(): + break + if not first_user_text: + return "" + lower = first_user_text.lower() + wants_read = any(v in lower for v in _READ_VERBS) + wants_write = any(v in lower for v in _WRITE_VERBS) + if not (wants_read and wants_write): + return "" + # 2. Check history for at least one Read tool_use with non-trivial result, AND no Write/Edit yet. + read_done = False + write_done = False + read_alias_names = {"Read", "fs_open_file", "ReadX"} + write_alias_names = {"Write", "Edit", "NotebookEdit", "fs_put_file", "fs_patch_file", "notebook_patch", "WriteX", "EditX"} + for m in messages: + content = m.get("content") if isinstance(m, dict) else None + if not isinstance(content, list): + continue + for part in content: + if not isinstance(part, dict): + continue + if part.get("type") == "tool_use": + tname = part.get("name", "") + if tname in read_alias_names: + read_done = True + elif tname in write_alias_names: + write_done = True + # Also: scan assistant text for textual tool_use markers (Qwen bridge history renders as text) + if isinstance(m, dict) and m.get("role") == "assistant": + plain = _extract_text(m.get("content", ""), client_profile=client_profile) + if "##TOOL_CALL##" in plain: + if any(f'"name": "{n}"' in plain for n in read_alias_names): + read_done = True + if any(f'"name": "{n}"' in plain for n in write_alias_names): + write_done = True + if not read_done or write_done: + return "" + return ( + "[STATE NOTICE — MUST OBEY]\n" + "The user's CURRENT TASK explicitly requires TWO operations: reading AND writing/editing.\n" + "You have ALREADY completed the read (the file content is in the history above).\n" + f"Your NEXT output MUST be a {to_qwen_name('Write')}/{to_qwen_name('Edit')} tool call in the required ##TOOL_CALL## format.\n" + "DO NOT summarize. DO NOT explain. DO NOT ask for confirmation. DO NOT output plain text.\n" + f"If you output anything other than a ##TOOL_CALL## block for {to_qwen_name('Write')}/{to_qwen_name('Edit')}, the user's task FAILS." + ) + + +def _extract_text_content(content) -> str: + """Flatten Anthropic content array/string → plain text.""" + if isinstance(content, str): + return content + if isinstance(content, list): + parts = [] + for p in content: + if isinstance(p, dict) and p.get("type") == "text": + parts.append(p.get("text", "")) + return "".join(parts) + return "" + + +def _resolve_cache_hints(messages: list) -> list: + """当 Claude Code 发来 'File unchanged since last read' 提示语时, + 用代理侧缓存的上一次真实 Read 结果回填,避免下游 Qwen 因缺少内容死循环。 + + - 正向:遇到非提示语的 Read tool_result,按 file_path 写入缓存 + - 反向:遇到提示语 tool_result,按 file_path 查缓存;命中则替换 content 为真实内容 + - 未命中时保留原提示语(Qwen 至少知道"已经读过"这个事实) + """ + if not messages: + return messages + ctx = get_request_context() + session_key = ctx.get("api_key", "") or "" + + # pass 1: tool_use_id -> file_path (only Read-like tools) + toolu_to_path: dict[str, str] = {} + READ_TOOL_NAMES = {"Read", "fs_open_file", "ReadX"} # ReadX kept for back-compat with in-flight sessions + for msg in messages: + content = msg.get("content") if isinstance(msg, dict) else None + if not isinstance(content, list): + continue + for part in content: + if not isinstance(part, dict): + continue + if part.get("type") == "tool_use" and part.get("name") in READ_TOOL_NAMES: + tid = part.get("id") + fpath = (part.get("input") or {}).get("file_path") or (part.get("input") or {}).get("path") + if tid and fpath: + toolu_to_path[tid] = fpath + + # pass 2: populate cache with real content AND rewrite hint-only results + rewritten = 0 + populated = 0 + out_messages: list = [] + for msg in messages: + if not isinstance(msg, dict): + out_messages.append(msg) + continue + content = msg.get("content") + if not isinstance(content, list): + out_messages.append(msg) + continue + new_content = [] + mutated = False + for part in content: + if not isinstance(part, dict) or part.get("type") != "tool_result": + new_content.append(part) + continue + tid = part.get("tool_use_id", "") + fpath = toolu_to_path.get(tid) + inner = part.get("content", "") + inner_text = inner if isinstance(inner, str) else _extract_text_content(inner) + + if fpath and inner_text and not file_content_cache.is_cache_hint(inner_text): + # real content → cache it + file_content_cache.put(session_key, fpath, inner_text) + populated += 1 + new_content.append(part) + continue + + if fpath and inner_text and file_content_cache.is_cache_hint(inner_text): + cached = file_content_cache.get(session_key, fpath) + if cached: + new_part = dict(part) + # Preserve the hint as a small header so the model knows this came + # from the cache, followed by the real content. + new_part["content"] = ( + f"[Proxy cache: previously read content of {fpath}]\n{cached}" + ) + new_content.append(new_part) + mutated = True + rewritten += 1 + continue + + new_content.append(part) + if mutated: + new_msg = dict(msg) + new_msg["content"] = new_content + out_messages.append(new_msg) + else: + out_messages.append(msg) + + if rewritten or populated: + log.info(f"[CacheHint] populated={populated} rewritten={rewritten} session={'set' if session_key else 'global'}") + return out_messages + + +def _apply_topic_isolation(messages: list, client_profile: str) -> list: + """若最新有文本的 user 消息与历史首条有文本的 user 消息实体无重合,判定为新任务。 + 保留 system 消息 + **最新 user 所在位置及之后的所有消息**(这样新任务自己产生的 + 工具链 tool_use/tool_result 不会被误砍掉)。""" + if not messages or len(messages) < 3: + return messages + # 找首条有实文本的 user + first_user = None + first_user_text = "" + for m in messages: + if isinstance(m, dict) and m.get("role") == "user": + txt = _extract_user_text_only(m.get("content", ""), client_profile=client_profile).strip() + if txt: + first_user = m + first_user_text = txt + break + if first_user is None: + return messages + # 最新有实文本的 user —— 并记下它在 messages 里的位置 + last_user = None + last_user_text = "" + last_user_idx = -1 + for idx in range(len(messages) - 1, -1, -1): + m = messages[idx] + if isinstance(m, dict) and m.get("role") == "user": + txt = _extract_user_text_only(m.get("content", ""), client_profile=client_profile).strip() + if txt: + last_user = m + last_user_text = txt + last_user_idx = idx + break + if last_user is None or last_user is first_user: + return messages + if not detect_topic_change(first_user_text, last_user_text): + return messages + # 话题切换:保留 system + 从 last_user 开始到末尾的所有消息 + # (这包含新任务自己产生的 tool_use/tool_result 工具链) + system_msgs = [m for m in messages if isinstance(m, dict) and m.get("role") == "system"] + tail = messages[last_user_idx:] + isolated = system_msgs + tail + dropped = len(messages) - len(isolated) + if dropped > 0: + log.info( + f"[话题隔离] 检测到新任务,丢弃 {dropped} 条旧历史(保留新任务工具链 {len(tail)} 条)。" + f"旧任务={first_user_text[:60]!r} 新任务={last_user_text[:60]!r}" + ) + return isolated + + +def messages_to_prompt(req_data: dict, *, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> PromptBuildResult: + resolved_client_profile = client_profile + raw_messages = req_data.get("messages", []) + # 话题隔离:新任务与历史首条 user 实体零重合时,丢弃所有历史,只保留 system + 最新 user。 + # 这解决 Claude Code 同 session 多任务时旧对话干扰新任务的问题。 + isolated = _apply_topic_isolation(raw_messages, resolved_client_profile) + # Pass: 历史拒绝清洗 + cleaned_messages, cleaned_count = clean_refusal_messages(isolated) + if cleaned_count: + log.info(f"[拒绝清洗] 替换了 {cleaned_count} 条 assistant 拒绝消息") + # Pass: 文件缓存回填 + messages = _resolve_cache_hints(cleaned_messages) + tools = _normalize_tools(req_data.get("tools", [])) + tool_enabled = bool(tools) + system_prompt = "" + sys_field = req_data.get("system", "") + if isinstance(sys_field, list): + system_prompt = " ".join(p.get("text", "") for p in sys_field if isinstance(p, dict)) + elif isinstance(sys_field, str): + system_prompt = sys_field + if not system_prompt: + for msg in messages: + if msg.get("role") == "system": + system_prompt = _extract_text(msg.get("content", ""), client_profile=client_profile) + break + return PromptBuildResult( + prompt=build_prompt_with_tools(system_prompt, messages, tools, client_profile=client_profile), + tools=tools, + tool_enabled=tool_enabled, + ) diff --git a/backend/services/qwen_client.py b/backend/services/qwen_client.py new file mode 100644 index 0000000000000000000000000000000000000000..de3c4ce262f1fb793a9fe35661be3c6d694a8ea0 --- /dev/null +++ b/backend/services/qwen_client.py @@ -0,0 +1,1059 @@ +import asyncio +import json +import logging +import os +import time +from typing import AsyncIterator + +import httpx +from playwright.async_api import async_playwright + +from backend.core.account_pool import AccountPool +from backend.services.auth_resolver import BASE_URL, AuthResolver +from backend.upstream.payload_builder import build_chat_payload +from backend.upstream.qwen_executor import QwenExecutor +from backend.upstream.sse_consumer import parse_sse_chunk + +log = logging.getLogger("qwen2api.client") + +# Cookie 持久化文件 +_COOKIE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "data", "browser_cookies.json") + +# 流式请求超时(真流式:只约束"连接"和"两次数据块之间的最大空闲", +# 不再对整个响应设硬上限,避免长任务/agent 工作跑到一半被整体超时杀掉)。 +_CHAT_STREAM_CONNECT_TIMEOUT = float(os.getenv("QWEN_STREAM_CONNECT_TIMEOUT", "30")) +_CHAT_STREAM_IDLE_TIMEOUT = float(os.getenv("QWEN_STREAM_IDLE_TIMEOUT", "180")) + + +class QwenClient: + def __init__(self, account_pool: AccountPool): + self.account_pool = account_pool + self.auth_resolver = AuthResolver(account_pool) if account_pool is not None else None + self.executor = QwenExecutor(self, account_pool) + + # httpx 用于非流式 API 调用(不会被 WAF 拦截) + limits = httpx.Limits(max_connections=50, max_keepalive_connections=10, keepalive_expiry=30.0) + timeout = httpx.Timeout(connect=30.0, read=60.0, write=30.0, pool=30.0) + self._http_client = httpx.AsyncClient( + limits=limits, timeout=timeout, http2=False, follow_redirects=True, + ) + + # Playwright 用于流式聊天请求(httpx 会被 WAF 拦截) + self._pw_playwright = None + self._pw_browser = None + self._pw_context = None + self._pw_main_page = None # 长期有效的已通过 WAF 挑战的主页面 + self._pw_init_lock = asyncio.Lock() + self._waf_cleared = False # 标记 WAF 是否已通过 + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + # 关闭 HTTP 连接池前保存 cookie + await self._save_cookies() + if self._http_client: + await self._http_client.aclose() + if self._pw_main_page: + await self._pw_main_page.close() + if self._pw_context: + await self._pw_context.close() + if self._pw_browser: + await self._pw_browser.close() + if self._pw_playwright: + await self._pw_playwright.stop() + return False + + async def _ensure_browser(self): + """延迟初始化 Playwright 浏览器(仅流式请求时使用)。 + + 环境变量 BROWSER_HEADED=1 时打开可见窗口,用于手动 captcha 求解。 + Cookie 自动持久化到 data/browser_cookies.json,重启后保留登录态。 + + 使用 asyncio.Lock 防止并发请求同时初始化浏览器。 + """ + if self._pw_context is not None: + return self._pw_context + + async with self._pw_init_lock: + # 双重检查:获取锁后再次检查是否已被其他协程初始化 + if self._pw_context is not None: + return self._pw_context + + headed = os.getenv("BROWSER_HEADED", "").lower() in ("1", "true", "yes") + self._pw_playwright = await async_playwright().start() + self._pw_browser = await self._pw_playwright.chromium.launch( + headless=not headed, + args=["--no-sandbox", "--disable-blink-features=AutomationControlled"], + ) + import os as _os + _proxy = _os.getenv("PLAYWRIGHT_PROXY") or _os.getenv("HTTP_PROXY") or _os.getenv("HTTPS_PROXY") + _ctx_kwargs = { + "viewport": {"width": 1920, "height": 1080}, + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36", + "locale": "zh-CN", + "timezone_id": "Asia/Shanghai", + } + if _proxy: + _ctx_kwargs["proxy"] = {"server": _proxy} + log.info("[QwenClient] Playwright 代理已配置: %s", _proxy) + self._pw_context = await self._pw_browser.new_context(**_ctx_kwargs) + await self._pw_context.add_init_script(""" + Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); + Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); + """) + + # 恢复持久化的 cookie + await self._load_cookies() + + log.info(f"[QwenClient] Playwright 浏览器已初始化 (headed={headed})") + if headed: + log.info(f"[QwenClient] 浏览器窗口已打开,请在浏览器中手动登录 Qwen 并完成验证码") + log.info(f"[QwenClient] 访问 {BASE_URL}/ 并设置 token 到 localStorage") + return self._pw_context + + async def _load_cookies(self): + """从磁盘加载持久化的 cookie。""" + try: + if os.path.exists(_COOKIE_FILE): + with open(_COOKIE_FILE, "r", encoding="utf-8") as f: + cookies = json.load(f) + if cookies: + await self._pw_context.add_cookies(cookies) + log.info(f"[QwenClient] 已恢复 {len(cookies)} 个持久化 cookie") + except Exception as e: + log.warning(f"[QwenClient] 加载 cookie 失败: {e}") + + async def _save_cookies(self): + """将当前 context 的 cookie 持久化到磁盘。""" + try: + if self._pw_context is None: + return + cookies = await self._pw_context.cookies() + os.makedirs(os.path.dirname(_COOKIE_FILE), exist_ok=True) + with open(_COOKIE_FILE, "w", encoding="utf-8") as f: + json.dump(cookies, f, ensure_ascii=False, indent=2) + log.info(f"[QwenClient] 已持久化 {len(cookies)} 个 cookie 到 {_COOKIE_FILE}") + except Exception as e: + log.warning(f"[QwenClient] 保存 cookie 失败: {e}") + + @staticmethod + def _load_bx_pool() -> list[dict]: + """加载 bx_pool.json(多 bx-ua 轮换池,降低风控概率)。""" + import os, json as _json, time as _time + try: + project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + pool_path = os.path.join(project_root, "bx_pool.json") + now = _time.time() + cache = getattr(QwenClient, "_bx_pool_cache", None) + if cache and now - cache["loaded_at"] < 60: + return cache["pool"] + if not os.path.exists(pool_path): + QwenClient._bx_pool_cache = {"pool": [], "loaded_at": now} + return [] + with open(pool_path, "r", encoding="utf-8") as f: + pool = _json.load(f) + QwenClient._bx_pool_cache = {"pool": pool, "loaded_at": now} + return pool + except Exception: + return [] + + @staticmethod + def _build_headers(token: str) -> dict[str, str]: + """构建 httpx 请求头(含 bx 反爬头)。""" + import os, uuid, random + pool = QwenClient._load_bx_pool() + entry = random.choice(pool) if pool else {} + ua = entry.get("user_agent") or os.getenv( + "QWEN_USER_AGENT", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36", + ) + bx_ua = entry.get("bx_ua") or os.getenv("QWEN_BX_UA", "") + bx_umid = entry.get("bx_umidtoken") or os.getenv("QWEN_BX_UMIDTOKEN", "") + bx_v = entry.get("bx_v") or os.getenv("QWEN_BX_V", "") + version = entry.get("web_version") or os.getenv("QWEN_WEB_VERSION", "") + timezone = entry.get("timezone") or os.getenv("QWEN_TIMEZONE", "") + + headers = { + "Authorization": f"Bearer {token}", + "User-Agent": ua, + "Accept": "application/json, text/plain, */*", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Referer": f"{BASE_URL}/", + "Origin": BASE_URL, + "Connection": "keep-alive", + "Content-Type": "application/json", + "source": "web", + "X-Request-Id": str(uuid.uuid4()), + } + if bx_ua: + headers["bx-ua"] = bx_ua + if bx_umid: + headers["bx-umidtoken"] = bx_umid + if bx_v: + headers["bx-v"] = bx_v + if version: + headers["Version"] = version + if timezone: + headers["Timezone"] = timezone + # 注入浏览器 cookie,降低 WAF 拦截概率(与网页会话对齐) + try: + if os.path.exists(_COOKIE_FILE): + with open(_COOKIE_FILE, "r", encoding="utf-8") as f: + cookies = json.load(f) + if isinstance(cookies, list) and cookies: + cookie_str = "; ".join( + f"{c.get('name')}={c.get('value')}" + for c in cookies + if c.get("name") and c.get("value") + ) + if cookie_str: + headers["Cookie"] = cookie_str + except Exception: + pass + return headers + + # ======================================================================== + # 非流式 API 请求:使用 httpx(WAF 通常不拦截 GET/DELETE,POST 尝试后降级) + # ======================================================================== + async def _request_json(self, method: str, path: str, token: str, body: dict | None = None, timeout: float = 30.0) -> dict: + """发送非流式 API 请求。 + + 使用 httpx 发送所有非流式请求(create_chat, list_chats, delete_chat 等), + 旧的 page.evaluate(fetch) 方式已被 Qwen BaXia 拦截导致挂起。 + 流式请求(chat/completions)走独立的 _browser_request_json。 + + 如果 httpx 返回 WAF 挑战页面,尝试浏览器备用路径。 + """ + try: + resp = await self._http_client.request( + method, + f"{BASE_URL}{path}", + headers=self._build_headers(token), + json=body, + timeout=timeout, + ) + body_text = resp.text + status = resp.status_code + + # 检测 WAF 拦截 + is_waf, waf_type = self._is_waf_challenge(body_text) + if is_waf: + log.warning("[QwenClient] httpx 请求被 WAF 拦截 (type=%s, status=%d, path=%s)", waf_type, status, path) + # 如果浏览器已初始化且通过了 WAF,尝试用浏览器 API 重试 + if self._pw_context is not None and self._waf_cleared: + log.info("[QwenClient] 尝试通过浏览器 ApiRequest 重试...") + browser_result = await self._browser_request_json( + method, f"{BASE_URL}{path}", token, body=body, timeout=timeout + ) + return browser_result + # 否则返回 WAF 错误 + return {"status": status, "body": body_text, "waf": waf_type} + + return {"status": status, "body": body_text} + except httpx.TimeoutException: + log.warning("[QwenClient] httpx 请求超时 (path=%s, timeout=%s)", path, timeout) + # 超时后尝试浏览器路径 + if self._pw_context is not None and self._waf_cleared: + log.info("[QwenClient] httpx 超时,尝试通过浏览器 ApiRequest 重试...") + browser_result = await self._browser_request_json( + method, f"{BASE_URL}{path}", token, body=body, timeout=timeout + ) + return browser_result + return {"status": 0, "body": f"httpx timeout ({timeout}s)"} + except Exception as e: + log.warning(f"[QwenClient] _request_json 异常: {e}") + return {"status": 0, "body": str(e)} + + async def create_chat(self, token: str, model: str, chat_type: str = "t2t") -> str: + return await self.executor.create_chat(token, model, chat_type=chat_type) + + async def delete_chat(self, token: str, chat_id: str): + await self._request_json("DELETE", f"/api/v2/chats/{chat_id}", token, timeout=20.0) + + async def list_chats(self, token: str, limit: int = 50) -> list[dict]: + res = await self._request_json("GET", f"/api/v2/chats?limit={limit}", token, timeout=20.0) + if res["status"] != 200: + return [] + try: + data = json.loads(res.get("body", "{}")) + except Exception: + return [] + chats = data.get("data", []) + return chats if isinstance(chats, list) else [] + + async def get_chat(self, token: str, chat_id: str) -> dict: + res = await self._request_json("GET", f"/api/v2/chats/{chat_id}", token, timeout=30.0) + if res["status"] != 200: + raise Exception(f"get_chat HTTP {res['status']}: {res.get('body', '')[:200]}") + try: + return json.loads(res.get("body", "{}")) + except Exception as e: + raise Exception(f"get_chat parse error: {e}, body={res.get('body', '')[:200]}") + + async def get_task_status(self, token: str, task_id: str) -> dict: + # 1) httpx + res = await self._request_json("GET", f"/api/v1/tasks/status/{task_id}", token, timeout=30.0) + body = res.get("body", "") or "" + status = res.get("status", 0) + is_waf, _ = self._is_waf_challenge(body) + if status == 200 and not is_waf: + try: + return json.loads(body) + except Exception as e: + raise Exception(f"task status parse error: {e}, body={body[:200]}") + + # 2) curl_cffi + bx + try: + from curl_cffi.requests import AsyncSession + headers = self._build_headers(token) + async with AsyncSession(impersonate="chrome131", timeout=30.0) as session: + resp = await session.get( + f"{BASE_URL}/api/v1/tasks/status/{task_id}", + headers=headers, + ) + if resp.status_code == 200 and not self._is_waf_challenge(resp.text or "")[0]: + return resp.json() + status = resp.status_code + body = resp.text or body + except Exception as e: + log.warning("[QwenClient] get_task_status curl_cffi failed: %s", e) + + # 3) browser fallback + br = await self._browser_request_json( + "GET", + f"{BASE_URL}/api/v1/tasks/status/{task_id}", + token, + timeout=30.0, + ) + if br.get("status") == 200: + try: + return json.loads(br.get("body", "{}")) + except Exception as e: + raise Exception(f"task status parse error: {e}, body={br.get('body', '')[:200]}") + + raise Exception(f"task status HTTP {status or br.get('status', 0)}: {body[:200]}") + + async def complete_once( + self, + token: str, + chat_id: str, + model: str, + content: str, + has_custom_tools: bool = False, + files: list[dict] | None = None, + chat_type: str = "t2t", + size: str | None = None, + img_url: str | None = None, + ) -> dict: + """完成一次生成(t2t/t2i/t2v)。 + + 上游 t2i/t2v 对 stream=false 常返回 Bad_Request; + 这里强制 stream=true,再把 SSE 聚合成 dict 供 images/videos 解析 URL/task_id。 + """ + payload = build_chat_payload( + chat_id, + model, + content, + has_custom_tools, + files=files, + chat_type=chat_type, + size=size, + img_url=img_url, + ) + # t2i: stream=true 直接出图 URL + # t2v/i2v: stream=false 才能拿到 task_id(stream=true 常空答) + # t2t: stream=true + prefer_stream = chat_type not in {"t2v", "i2v"} + attempts = [True] if prefer_stream else [False, True] + if prefer_stream: + attempts = [True, False] + + body_text = "" + status = 0 + last_err = "" + for use_stream in attempts: + payload["stream"] = use_stream + payload["incremental_output"] = True + # 1) curl_cffi + curl_res = await self._stream_chat_via_curl_cffi(token, chat_id, payload, timeout=300.0) + if curl_res and curl_res.get("status") == 200 and not self._is_waf_challenge(curl_res.get("body") or "")[0]: + status = 200 + body_text = curl_res.get("body") or "" + else: + # 2) httpx + res = await self._request_json( + "POST", + f"/api/v2/chat/completions?chat_id={chat_id}", + token, + payload, + timeout=300.0, + ) + status = res.get("status", 0) + body_text = res.get("body", "") or "" + is_waf, _ = self._is_waf_challenge(body_text) + if status != 200 or is_waf: + # 3) browser + br = await self._browser_request_json( + "POST", + f"{BASE_URL}/api/v2/chat/completions?chat_id={chat_id}", + token, + body=payload, + timeout=300.0, + ) + status = br.get("status", 0) + body_text = br.get("body", "") or "" + + if status != 200: + last_err = f"HTTP {status}: {body_text[:200]}" + continue + + # 判断是否有实质内容:task_id / 媒体 URL / 非空 answer + has_task = ("task_id" in body_text) or ("taskId" in body_text) + has_media = any(x in body_text for x in (".mp4", ".png", ".jpg", "cdn.qwenlm.ai", "/t2i/", "/t2v/")) + empty_answer = ( + '"content": ""' in body_text + and "task_id" not in body_text + and "cdn.qwenlm.ai" not in body_text + ) + # 对 t2v:空答则换下一种 stream 模式 + if chat_type in {"t2v", "i2v"} and not has_task and not has_media and empty_answer: + last_err = "empty t2v answer without task_id" + log.warning("[complete_once] t2v empty with stream=%s, try next mode", use_stream) + continue + break + else: + raise Exception(f"complete_once failed: {last_err or 'unknown'}") + + if status != 200: + raise Exception(f"complete_once HTTP {status}: {body_text[:300]}") + + # SSE 文本:聚合成可解析结构 + events: list[dict] = [] + for line in body_text.splitlines(): + line = line.strip() + if not line.startswith("data:"): + continue + data_str = line[5:].strip() + if not data_str or data_str == "[DONE]": + continue + try: + events.append(json.loads(data_str)) + except Exception: + events.append({"raw": data_str}) + + if not events: + try: + return json.loads(body_text) + except Exception: + return {"raw_sse": body_text, "events": [], "success": True} + + return {"raw_sse": body_text, "events": events, "success": True} + + async def verify_token(self, token: str) -> bool: + if not token: + return False + try: + resp = await self._http_client.get( + f"{BASE_URL}/api/v1/auths/", + headers=self._build_headers(token), + timeout=15.0, + ) + if resp.status_code != 200: + return False + try: + data = resp.json() + return data.get("role") == "user" + except Exception as e: + log.warning(f"[verify_token] JSON 解析失败: {e}, status={resp.status_code}, text={resp.text[:100]}") + if "aliyun_waf" in resp.text.lower() or " list: + try: + resp = await self._http_client.get( + f"{BASE_URL}/api/models", + headers=self._build_headers(token), + timeout=10.0, + ) + if resp.status_code != 200: + return [] + try: + return resp.json().get("data", []) + except Exception as e: + log.warning(f"[list_models] JSON 解析失败: {e}") + return [] + except Exception: + return [] + + # ---- cached upstream-pool model list ---- + _UPSTREAM_MODELS_TTL = 300 + _upstream_models_cache: list[dict] = [] + _upstream_models_fetched_at: float = 0.0 + + async def list_models_from_pool(self) -> list[dict]: + now = time.time() + if self._upstream_models_cache and (now - self._upstream_models_fetched_at) < self._UPSTREAM_MODELS_TTL: + return self._upstream_models_cache + if self.account_pool is None: + return [] + acc = None + try: + acc = await self.account_pool.acquire_wait(timeout=5) + if not acc: + return [] + models = await self.list_models(acc.token) + if models: + QwenClient._upstream_models_cache = models + QwenClient._upstream_models_fetched_at = now + return models + except Exception as e: + log.warning(f"[list_models_from_pool] failed: {e}") + return [] + finally: + if acc is not None: + self.account_pool.release(acc) + + def _build_payload( + self, + chat_id: str, + model: str, + content: str, + has_custom_tools: bool = False, + files: list[dict] | None = None, + chat_type: str = "t2t", + size: str | None = None, + ) -> dict: + return build_chat_payload( + chat_id, + model, + content, + has_custom_tools, + files=files, + chat_type=chat_type, + size=size, + ) + + def parse_sse_chunk(self, chunk: str) -> list[dict]: + return parse_sse_chunk(chunk) + + async def stream(self, token: str, chat_id: str, model: str, content: str, has_custom_tools: bool = False, files: list[dict] | None = None): + async for event in self.executor.stream(token, chat_id, model, content, has_custom_tools, files=files): + yield event + + async def chat_stream_events_with_retry( + self, + model: str, + content: str, + has_custom_tools: bool = False, + files: list[dict] | None = None, + fixed_account=None, + existing_chat_id: str | None = None, + ): + """转发到 executor.chat_stream_events_with_retry(带重试的流式聊天)。""" + async for item in self.executor.chat_stream_events_with_retry( + model, content, + has_custom_tools=has_custom_tools, + files=files, + fixed_account=fixed_account, + existing_chat_id=existing_chat_id, + ): + yield item + + # ======================================================================== + # WAF 检测 + # ======================================================================== + def _is_waf_challenge(self, text: str) -> tuple[bool, str]: + """检测响应是否为 WAF 挑战页面。返回 (is_waf, challenge_type)。""" + if not text: + return False, "" + if "FAIL_SYS_USER_VALIDATE" in text: + return True, "punish" + if "aliyun_waf_aa" in text or "aliyun_waf_bb" in text: + return True, "aa_bb" + if "captcha" in text.lower() and ("sliding" in text.lower() or "滑块" in text): + return True, "captcha" + if " dict: + """通过浏览器 page.evaluate 使用 window.ApiRequest 发送请求。 + + Qwen 前端的 window.ApiRequest 是官方 API 客户端,自动处理: + - bx-* 安全头的注入(通过 BaXia 集成) + - 请求签名和时间戳 + - 会话身份验证 + + 相比直接使用 window.fetch(被 BaXia 包裹导致挂起),ApiRequest 是受支持的途径。 + 如果 ApiRequest 不可用,降级到 window.fetch。 + """ + main_page = await self._ensure_main_page() + + # 设置 token 到 localStorage(Qwen 前端需要) + escaped_token = token.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n") + try: + await main_page.evaluate(f"localStorage.setItem('token', '{escaped_token}')") + except Exception: + pass + + # 安全的字符串转义 + def _js_str(s): + return s.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n") + + safe_url = _js_str(url) + safe_method = _js_str(method) + safe_token = escaped_token + + body_json = "" + if body is not None: + body_json = json.dumps(body, ensure_ascii=False) + + timeout_ms = int(timeout * 1000) + + # 构建 JS:优先使用 window.ApiRequest,降级到 window.fetch + # ApiRequest API(从运行时检测得出): + # ApiRequest.post(url, bodyObj, opts) → POST with object body + # ApiRequest.postBody(url, bodyStr, opts) → POST with string body + # ApiRequest.request(method, url, opts) → generic (no body) + # ApiRequest.requestBody(method, url, bodyStr, opts) → generic with string body + has_body = body is not None + if has_body: + # 使用 JSON.parse/stringify 确保 body_json 在 JS 中可用 + request_js = f""" +(async () => {{ + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), {timeout_ms}); + try {{ + const useApiRequest = typeof window.ApiRequest !== 'undefined' && typeof window.ApiRequest.postBody === 'function'; + + if (useApiRequest) {{ + // 使用 Qwen 官方 ApiRequest(自动处理 bx-* 安全头) + // postBody 接受 (url, bodyString, opts) —— body 以字符串传递 + const resp = await window.ApiRequest.postBody( + '{safe_url}', + '{_js_str(body_json)}', + {{ + headers: {{ + 'Authorization': 'Bearer {safe_token}', + 'Content-Type': 'application/json', + }}, + signal: controller.signal, + }} + ); + clearTimeout(id); + // ApiRequest 返回的响应可能有不同格式 + if (typeof resp.json === 'function') {{ + const data = await resp.json(); + return {{ status: resp.status || 200, body: JSON.stringify(data) }}; + }} else if (typeof resp.text === 'function') {{ + const text = await resp.text(); + return {{ status: resp.status || 200, body: text }}; + }} else {{ + return {{ status: 200, body: JSON.stringify(resp) }}; + }} + }} else {{ + // 降级到 window.fetch(可能被 BaXia 拦截或挂起) + const resp = await fetch('{safe_url}', {{ + method: '{safe_method}', + headers: {{ + 'Authorization': 'Bearer {safe_token}', + 'Content-Type': 'application/json', + 'Accept': 'application/json, text/plain, */*', + 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', + 'Origin': '{_js_str(BASE_URL)}', + 'Referer': '{_js_str(BASE_URL)}/', + 'source': 'web', + }}, + body: '{_js_str(body_json)}', + signal: controller.signal, + credentials: 'include', + }}); + clearTimeout(id); + const text = await resp.text(); + return {{ status: resp.status, body: text }}; + }} + }} catch (e) {{ + clearTimeout(id); + return {{ status: 0, body: e.toString() }}; + }} +}})() +""" + else: + # 没有 body 的请求(GET/DELETE) + request_js = f""" +(async () => {{ + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), {timeout_ms}); + try {{ + const useApiRequest = typeof window.ApiRequest !== 'undefined' && typeof window.ApiRequest.request === 'function'; + + if (useApiRequest) {{ + const resp = await window.ApiRequest.request( + '{safe_method}', + '{safe_url}', + {{ + headers: {{ + 'Authorization': 'Bearer {safe_token}', + }}, + signal: controller.signal, + }} + ); + clearTimeout(id); + if (typeof resp.json === 'function') {{ + const data = await resp.json(); + return {{ status: resp.status || 200, body: JSON.stringify(data) }}; + }} else if (typeof resp.text === 'function') {{ + const text = await resp.text(); + return {{ status: resp.status || 200, body: text }}; + }} else {{ + return {{ status: 200, body: JSON.stringify(resp) }}; + }} + }} else {{ + const resp = await fetch('{safe_url}', {{ + method: '{safe_method}', + headers: {{ + 'Authorization': 'Bearer {safe_token}', + 'Accept': 'application/json, text/plain, */*', + 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', + 'Origin': '{_js_str(BASE_URL)}', + 'Referer': '{_js_str(BASE_URL)}/', + 'source': 'web', + }}, + signal: controller.signal, + credentials: 'include', + }}); + clearTimeout(id); + const text = await resp.text(); + return {{ status: resp.status, body: text }}; + }} + }} catch (e) {{ + clearTimeout(id); + return {{ status: 0, body: e.toString() }}; + }} +}})() +""" + log.info("[QwenClient] browser_fetch: 发送 %s %s ... (useApiRequest=%s)", method, url.split('?')[0], "yes") + try: + result = await asyncio.wait_for( + main_page.evaluate(request_js), + timeout=timeout + 5.0, # 额外 5 秒用于 JS 执行开销 + ) + status = result.get("status", 0) + body_len = len(result.get("body", "")) + log.info("[QwenClient] browser_fetch 完成: status=%d 长度=%d", status, body_len) + if body_len > 0 and status != 0: + log.info("[QwenClient] browser_fetch 响应前100: %s", result.get("body", "")[:100]) + return result + except asyncio.TimeoutError: + log.error(f"[QwenClient] browser_fetch 超时 ({timeout}s)") + return {"status": 0, "body": f"browser fetch timeout ({timeout}s)"} + except Exception as e: + log.error(f"[QwenClient] browser_fetch 异常: {e}", exc_info=True) + return {"status": 0, "body": str(e)} + finally: + await self._save_cookies() + + # ======================================================================== + # 流式聊天请求 + # ======================================================================== + async def _stream_chat_via_curl_cffi(self, token: str, chat_id: str, payload: dict, timeout: float = 120.0) -> dict | None: + """优先走 curl_cffi(chrome131)+bx 头直连上游,避免 Playwright 超时。 + + 【缓冲模式】用于 t2i/t2v 等需要一次性拿到完整 SSE 再解析 task_id/URL 的场景。 + 用 (connect, idle) 元组超时:curl 在 stream 关闭时以 LOW_SPEED 语义判定, + 即"整段响应期间持续无数据"才中断,而不是对总时长设硬上限, + 因此长任务不会被拦腰截断。 + """ + try: + from curl_cffi.requests import AsyncSession + except Exception as e: + log.warning("[QwenClient] curl_cffi 不可用: %s", e) + return None + + headers = self._build_headers(token) + headers["Accept"] = "text/event-stream, application/json" + url = f"{BASE_URL}/api/v2/chat/completions?chat_id={chat_id}" + # 元组超时:(连接超时, 读取空闲超时);stream 关闭 → curl 用 LOW_SPEED_TIME=connect+idle + idle = max(timeout, _CHAT_STREAM_IDLE_TIMEOUT) + tup_timeout = (_CHAT_STREAM_CONNECT_TIMEOUT, idle) + try: + async with AsyncSession(impersonate="chrome131", timeout=tup_timeout) as session: + chunks: list[str] = [] + async with session.stream("POST", url, headers=headers, json=payload) as resp: + async for chunk in resp.aiter_content(): + if chunk: + chunks.append(chunk.decode("utf-8", errors="replace")) + status_code = resp.status_code + return {"status": status_code, "body": "".join(chunks)} + except Exception as e: + log.warning("[QwenClient] curl_cffi 流式请求失败: %s", e) + return None + + async def _stream_chat_via_curl_cffi_iter(self, token: str, chat_id: str, payload: dict): + """【真流式模式】逐块产出上游 SSE,用于对话流式返回。 + + 与缓冲版的区别:数据一到就 yield,客户端 SSE 连接持续有数据流动, + 不会因等待完整响应而空闲断连;同时用 (connect, idle) 元组超时, + 只在"长时间完全无新数据"时才中断,长任务/agent 全程不被总时长上限杀掉。 + + 产出: + {"status": int, "body": str} # 首个错误/WAF 状态帧(非 200 时) + {"chunk": str} # 正常 SSE 数据块 + """ + try: + from curl_cffi.requests import AsyncSession + except Exception as e: + log.warning("[QwenClient] curl_cffi 不可用: %s", e) + yield {"status": 0, "body": f"curl_cffi unavailable: {e}"} + return + + headers = self._build_headers(token) + headers["Accept"] = "text/event-stream, application/json" + url = f"{BASE_URL}/api/v2/chat/completions?chat_id={chat_id}" + tup_timeout = (_CHAT_STREAM_CONNECT_TIMEOUT, _CHAT_STREAM_IDLE_TIMEOUT) + try: + async with AsyncSession(impersonate="chrome131", timeout=tup_timeout) as session: + async with session.stream("POST", url, headers=headers, json=payload) as resp: + status_code = resp.status_code + if status_code != 200: + body_chunks: list[str] = [] + async for chunk in resp.aiter_content(): + if chunk: + body_chunks.append(chunk.decode("utf-8", errors="replace")) + yield {"status": status_code, "body": "".join(body_chunks)[:2000]} + return + async for chunk in resp.aiter_content(): + if chunk: + yield {"chunk": chunk.decode("utf-8", errors="replace")} + except Exception as e: + log.warning("[QwenClient] curl_cffi 真流式请求失败: %s", e) + yield {"status": 0, "body": str(e)} + + async def stream_chat_once(self, token: str, chat_id: str, payload: dict) -> AsyncIterator[dict]: + """流式聊天:优先 curl_cffi 真流式直连,失败再降级 Playwright ApiRequest。""" + # 先尝试真流式:逐块透传,遇到首个数据块即视为成功;非 200/WAF 再降级浏览器。 + first_error: dict | None = None + got_data = False + yielded_any = False # 是否已向下游 yield 过 chunk(用于只在首帧检测 WAF) + buffer = "" + async for item in self._stream_chat_via_curl_cffi_iter(token, chat_id, payload): + if "chunk" in item: + got_data = True + buffer += item["chunk"] + # 保持 SSE 事件边界(\n\n)切分后透传 + while "\n\n" in buffer: + msg, buffer = buffer.split("\n\n", 1) + # 尚未向下游发过任何数据时,若首帧命中 WAF 文本,转错误帧走降级 + if not yielded_any and self._is_waf_challenge(msg)[0]: + first_error = {"status": 403, "body": msg[:300]} + got_data = False + break + yield {"chunk": msg + "\n\n"} + yielded_any = True + if first_error is not None: + break + continue + # 状态帧(非 200 或 curl 失败) + status0 = item.get("status", 0) + body0 = item.get("body", "") or "" + first_error = {"status": status0, "body": body0} + break + + if got_data: + # flush 残留 buffer + if buffer.strip(): + yield {"chunk": buffer if buffer.endswith("\n\n") else buffer + "\n\n"} + return + + # 未取得任何数据 → 判定是否降级浏览器 + use_browser = True + if first_error is not None: + is_waf0, waf0 = self._is_waf_challenge(first_error.get("body", "") or "") + log.warning( + "[QwenClient] curl_cffi 真流式未取得数据 status=%s waf=%s,降级浏览器", + first_error.get("status"), waf0 or "-", + ) + + result = await self._browser_request_json( + "POST", + f"{BASE_URL}/api/v2/chat/completions?chat_id={chat_id}", + token, + body=payload, + timeout=_CHAT_STREAM_IDLE_TIMEOUT, + ) + + status = result.get("status", 0) + raw_text = result.get("body", "") + + # 检测 WAF 挑战 + is_waf, waf_type = self._is_waf_challenge(raw_text) + if is_waf: + log.warning("[QwenClient] 上游返回 WAF 挑战 (type=%s, status=%d)", waf_type, status) + if waf_type == "punish": + try: + data = json.loads(raw_text) + punish_url = data.get("data", {}).get("url", "") + if punish_url: + log.info("[QwenClient] 提取到 punish URL: %s", punish_url[:150]) + except Exception: + pass + yield {"status": 403, "body": f"WAF challenge ({waf_type}): {raw_text[:300]}"} + return + + if status != 200: + log.warning("[QwenClient] 上游 HTTP %d: %.200s", status, raw_text) + yield {"status": status, "body": raw_text[:500]} + return + + # 浏览器降级路径是缓冲返回:按原始字节流逐块输出(保持 SSE 格式) + buffer = "" + for chunk_text in [raw_text[i:i+4096] for i in range(0, len(raw_text), 4096)]: + buffer += chunk_text + while "\n\n" in buffer: + msg, buffer = buffer.split("\n\n", 1) + yield {"chunk": msg + "\n\n"} diff --git a/backend/services/refusal_cleaner.py b/backend/services/refusal_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc30fc374360f6bc03f3eeb2416576a18f58f05 --- /dev/null +++ b/backend/services/refusal_cleaner.py @@ -0,0 +1,125 @@ +"""历史拒绝清洗:扫描过往 assistant 消息里的拒绝/自我限制文本, +命中后把整条消息内容替换为占位工具调用,防止模型看到自己的拒绝模式并级联复现。 + +典型拒绝场景: + - "I'm sorry, I cannot help with that" + - "I only answer questions about Cursor" + - "我只能回答编程相关问题" + - "Tool X does not exist" (Qwen 自制错误) + - "I cannot execute this tool" +""" + +from __future__ import annotations + +import re + +_REFUSAL_PATTERNS: tuple[re.Pattern, ...] = ( + # ── 英文:道歉/拒绝 ── + re.compile(r"I[''\u2019]\s*m\s+sorry", re.IGNORECASE), + re.compile(r"I\s+am\s+sorry", re.IGNORECASE), + re.compile(r"I\s+cannot\s+help\s+with", re.IGNORECASE), + re.compile(r"I\s+can\s+only\s+answer", re.IGNORECASE), + re.compile(r"I\s+only\s+answer", re.IGNORECASE), + re.compile(r"not\s+able\s+to\s+fulfill", re.IGNORECASE), + re.compile(r"cannot\s+perform", re.IGNORECASE), + re.compile(r"cannot\s+write\s+files", re.IGNORECASE), + re.compile(r"not\s+able\s+to\s+search", re.IGNORECASE), + re.compile(r"I\s+cannot\s+search", re.IGNORECASE), + re.compile(r"outside\s+(?:my|the)\s+capabilities", re.IGNORECASE), + re.compile(r"beyond\s+(?:my|the)\s+scope", re.IGNORECASE), + re.compile(r"I[''\u2019]?m\s+not\s+(?:able|designed)\s+to", re.IGNORECASE), + re.compile(r"I\s+don[''\u2019]t\s+have\s+(?:the\s+)?(?:ability|capability)", re.IGNORECASE), + re.compile(r"(?:can[.']?t|cannot|unable\s+to)\s+help\s+with\s+(?:this|that)", re.IGNORECASE), + re.compile(r"scoped\s+to\s+(?:answering|helping)", re.IGNORECASE), + re.compile(r"falls\s+outside\s+(?:the\s+scope|what\s+I)", re.IGNORECASE), + + # ── 英文:Qwen 特有的工具错误幻觉 ── + re.compile(r"Tool\s+[\w.:-]+\s+does\s+not\s+exists?", re.IGNORECASE), + re.compile(r"I\s+cannot\s+execute\s+this\s+tool", re.IGNORECASE), + re.compile(r"tool\s+.+\s+is\s+not\s+available", re.IGNORECASE), + re.compile(r"the\s+tool\s+\S+\s+is\s+(?:not\s+)?registered", re.IGNORECASE), + + # ── 中文:身份/话题拒绝 ── + re.compile(r"我是\s*Cursor\s*的?\s*支持助手"), + re.compile(r"我的职责是帮助你解答"), + re.compile(r"我无法透露"), + re.compile(r"我只能回答"), + re.compile(r"无法提供.*信息"), + re.compile(r"我没有.*也不会提供"), + re.compile(r"(?:与|和)\s*(?:编程|代码|开发)\s*无关"), + re.compile(r"请提问.*(?:编程|代码|开发|技术).*问题"), + re.compile(r"只能帮助.*(?:编程|代码|开发)"), + + # ── 中文:工具调用相关 ── + re.compile(r"无法调用.*?工具"), + re.compile(r"工具.*?不存在"), + re.compile(r"我无法执行.*?工具"), + re.compile(r"我不能(?:运行|执行).*?函数"), +) + + +def is_refusal_text(text: str) -> bool: + if not text: + return False + return any(p.search(text) for p in _REFUSAL_PATTERNS) + + +def clean_refusal_messages( + messages: list, + *, + replacement_text: str = "", +) -> tuple[list, int]: + """扫 messages 里 assistant 角色的消息,若其纯文本内容命中拒绝模式则替换。 + + - 如果消息的 content 是字符串:整条替换为空或 replacement_text + - 如果 content 是 list of blocks:只替换其中的 text block;保留 tool_use / tool_result + (因为拒绝通常只出现在解释文本里,保留工具调用让 pair 完整) + - 如果消息已经包含 tool_use block,倾向于保留(那是正常的多步调用) + + 返回 (cleaned_messages, replacements_count) + """ + if not messages: + return messages, 0 + + placeholder = replacement_text or "[earlier assistant turn omitted by proxy]" + out: list = [] + replaced = 0 + for msg in messages: + if not isinstance(msg, dict) or msg.get("role") != "assistant": + out.append(msg) + continue + content = msg.get("content") + if isinstance(content, str): + if is_refusal_text(content): + new_msg = dict(msg) + new_msg["content"] = placeholder + out.append(new_msg) + replaced += 1 + else: + out.append(msg) + elif isinstance(content, list): + has_tool_use = any(isinstance(p, dict) and p.get("type") == "tool_use" for p in content) + new_content = [] + mutated = False + for part in content: + if isinstance(part, dict) and part.get("type") == "text": + txt = part.get("text", "") + if is_refusal_text(txt): + if has_tool_use: + # 保留 tool_use block,只删掉道歉文本 + mutated = True + continue + new_content.append({"type": "text", "text": placeholder}) + mutated = True + continue + new_content.append(part) + if mutated: + new_msg = dict(msg) + new_msg["content"] = new_content or [{"type": "text", "text": placeholder}] + out.append(new_msg) + replaced += 1 + else: + out.append(msg) + else: + out.append(msg) + return out, replaced diff --git a/backend/services/response_formatters.py b/backend/services/response_formatters.py new file mode 100644 index 0000000000000000000000000000000000000000..7abbc315a2de0947626598b5afed720da51e0ff0 --- /dev/null +++ b/backend/services/response_formatters.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import json +from typing import Any + +from backend.runtime.execution import build_tool_directive + + +def build_openai_completion_payload(*, completion_id: str, created: int, model_name: str, prompt: str, execution, standard_request) -> dict[str, Any]: + directive = build_tool_directive(standard_request, execution.state) + if directive.stop_reason == "tool_use": + oai_tool_calls = [ + { + "id": block["id"], + "type": "function", + "function": { + "name": block["name"], + "arguments": json.dumps(block.get("input", {}), ensure_ascii=False), + }, + } + for block in directive.tool_blocks + if block.get("type") == "tool_use" + ] + msg: dict[str, Any] = {"role": "assistant", "content": None, "tool_calls": oai_tool_calls} + finish_reason = "tool_calls" + else: + oai_tool_calls = [] + msg = {"role": "assistant", "content": execution.state.answer_text} + finish_reason = "stop" + + log_payload = [ + { + "id": call["id"], + "name": call["function"]["name"], + "arguments": call["function"]["arguments"], + } + for call in oai_tool_calls + ] + import logging + logging.getLogger("qwen2api.chat").info( + "[OAI] response finish_reason=%s tool_calls=%s text_preview=%r", + finish_reason, + log_payload, + execution.state.answer_text[:300], + ) + + return { + "id": completion_id, + "object": "chat.completion", + "created": created, + "model": model_name, + "choices": [{"index": 0, "message": msg, "finish_reason": finish_reason}], + "usage": { + "prompt_tokens": len(prompt), + "completion_tokens": len(execution.state.answer_text), + "total_tokens": len(prompt) + len(execution.state.answer_text), + }, + } + + +def build_anthropic_message_payload(*, msg_id: str, model_name: str, prompt: str, execution, standard_request) -> dict[str, Any]: + directive = build_tool_directive(standard_request, execution.state) + content_blocks: list[dict[str, Any]] = [] + if execution.state.reasoning_text: + content_blocks.append({"type": "thinking", "thinking": execution.state.reasoning_text}) + content_blocks.extend(directive.tool_blocks) + return { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": model_name, + "content": content_blocks, + "stop_reason": directive.stop_reason, + "stop_sequence": None, + "usage": {"input_tokens": len(prompt), "output_tokens": len(execution.state.answer_text)}, + } + + +def build_gemini_generate_payload(*, execution) -> dict[str, Any]: + return { + "candidates": [ + { + "content": { + "parts": [{"text": execution.state.answer_text}], + "role": "model", + } + } + ] + } diff --git a/backend/services/schema_compressor.py b/backend/services/schema_compressor.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1e5922ec485df717136a9a32b9e0ff8dc6e194 --- /dev/null +++ b/backend/services/schema_compressor.py @@ -0,0 +1,96 @@ +"""JSON Schema 压缩:把冗长的 JSON Schema 转成紧凑的 TypeScript-like 签名。 + +动机: + 一个完整 JSON Schema 工具定义(含 description、type、required、enum 等)单个约 + 1.5KB。90 个工具合计 ~135KB prompt。 + 压缩成 TS 签名后,单个工具约 150~250 bytes。90 个工具 ~15KB。**省 10 倍空间**。 + 输入越小,上游输出预算越多,截断率越低。 + +示例: + 输入 schema: + {"type":"object","properties":{ + "file_path":{"type":"string","description":"..."}, + "encoding":{"type":"string","enum":["utf-8","base64"]} + }, + "required":["file_path"]} + + 输出 TS 签名: + {file_path!: string, encoding?: utf-8|base64} + + `!` = required, `?` = optional +""" + +from __future__ import annotations + +from typing import Any + + +def _type_of(prop: dict[str, Any]) -> str: + """把单个 property 的类型压缩成简短字符串。""" + if not isinstance(prop, dict): + return "any" + + # enum:直接列值 + if "enum" in prop and isinstance(prop["enum"], list) and prop["enum"]: + vals = [] + for v in prop["enum"]: + if isinstance(v, str): + vals.append(v) + else: + vals.append(str(v)) + return "|".join(vals) + + base_type = prop.get("type", "any") + + # array:标注 item 类型 + if base_type == "array": + items = prop.get("items") + if isinstance(items, dict): + item_type = _type_of(items) + return f"{item_type}[]" + return "any[]" + + # object:嵌套对象 → 递归压缩 + if base_type == "object" and isinstance(prop.get("properties"), dict): + return compact_schema(prop) + + # union type(type 是 list) + if isinstance(base_type, list): + return "|".join(str(t) for t in base_type) + + return str(base_type) if base_type else "any" + + +def compact_schema(schema: dict[str, Any]) -> str: + """压缩一个 JSON Schema 为 TS-like 签名。 + + 返回示例:`{file_path!: string, encoding?: utf-8|base64}` + """ + if not isinstance(schema, dict): + return "{}" + props = schema.get("properties") + if not isinstance(props, dict) or not props: + return "{}" + required = set(schema.get("required", []) if isinstance(schema.get("required"), list) else []) + parts = [] + for name, spec in props.items(): + type_str = _type_of(spec if isinstance(spec, dict) else {}) + marker = "!" if name in required else "?" + parts.append(f"{name}{marker}: {type_str}") + return "{" + ", ".join(parts) + "}" + + +def render_tool_signature(tool: dict[str, Any], desc_max_len: int = 50) -> str: + """渲染单个工具为紧凑一行:"- name: desc\n Params: {...}"。""" + name = tool.get("name", "") + desc = (tool.get("description", "") or "").strip() + if desc_max_len > 0 and len(desc) > desc_max_len: + desc = desc[:desc_max_len] + "…" + schema = tool.get("parameters") or tool.get("input_schema") or {} + sig = compact_schema(schema) + line = f"- {name}" + if desc: + line += f": {desc}" + if sig and sig != "{}": + line += f"\n Params: {sig}" + return line diff --git a/backend/services/standard_request_builder.py b/backend/services/standard_request_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..55907f91d48afa498c4563514228117da1894ec9 --- /dev/null +++ b/backend/services/standard_request_builder.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from backend.adapter.standard_request import StandardRequest +from backend.core.config import resolve_model +from backend.services.prompt_builder import messages_to_prompt +from backend.toolcall.normalize import build_tool_name_registry + + +def build_chat_standard_request(req_data: dict, *, default_model: str, surface: str, client_profile: str = "openclaw_openai") -> StandardRequest: + requested_model = req_data.get("model", default_model) + prompt_result = messages_to_prompt(req_data, client_profile=client_profile) + tools = prompt_result.tools + tool_names = [tool_name for tool_name in (tool.get("name") for tool in tools) if isinstance(tool_name, str) and tool_name] + return StandardRequest( + prompt=prompt_result.prompt, + response_model=requested_model, + resolved_model=resolve_model(requested_model), + surface=surface, + client_profile=client_profile, + stream=req_data.get("stream", False), + tools=tools, + tool_names=tool_names, + tool_name_registry=build_tool_name_registry(tool_names), + tool_enabled=prompt_result.tool_enabled, + ) diff --git a/backend/services/task_session.py b/backend/services/task_session.py new file mode 100644 index 0000000000000000000000000000000000000000..82881402a4440d71b742803558a10f06a32a0f86 --- /dev/null +++ b/backend/services/task_session.py @@ -0,0 +1,411 @@ +from __future__ import annotations + +import hashlib +import json +import logging +from dataclasses import dataclass +from typing import Any + +from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE, StandardRequest +from backend.services.prompt_builder import _extract_text, _extract_user_text_only, _render_history_tool_call + +log = logging.getLogger("qwen2api.task_session") + + +@dataclass(slots=True) +class SessionHistoryEntry: + digest: str + rendered: str + + +@dataclass(slots=True) +class PersistentSessionPlan: + enabled: bool + reuse_chat: bool + prompt: str + full_prompt: str + current_hashes: list[str] + existing_chat_id: str | None + account_email: str | None + reason: str | None = None + existing_hash_count: int = 0 + new_entries_count: int = 0 + + +def should_use_persistent_tool_session(request: StandardRequest) -> bool: # noqa: ARG001 + # 禁用会话复用,对齐 ds2api 架构,避免续接 prompt 导致模型返回空输出 + # 每次请求都创建新的 chat,让上游自动管理会话历史 + return False + + +def persistent_session_disabled_reason(request: StandardRequest) -> str: # noqa: ARG001 + # 会话复用已全局禁用 + return "session_reuse_disabled_globally" + + +def _preview_identifier(value: str | None, *, head: int = 8, tail: int = 6) -> str: + if not value: + return "-" + text = str(value) + if len(text) <= head + tail + 3: + return text + return f"{text[:head]}...{text[-tail:]}" + + +def _log_session_plan(*, request: StandardRequest, surface: str, plan: PersistentSessionPlan) -> None: + log.info( + "[SessionPlan] surface=%s enabled=%s reuse_chat=%s reason=%s session=%s existing_chat=%s current_hashes=%s existing_hashes=%s new_entries=%s account=%s profile=%s tools=%s", + surface, + plan.enabled, + plan.reuse_chat, + plan.reason or '-', + _preview_identifier(getattr(request, 'session_key', None)), + _preview_identifier(plan.existing_chat_id), + len(plan.current_hashes), + plan.existing_hash_count, + plan.new_entries_count, + plan.account_email or getattr(request, 'bound_account_email', None) or '-', + getattr(request, 'client_profile', '-'), + list(getattr(request, 'tool_names', []) or [])[:6], + ) + + +def log_session_plan_reuse_cancelled(*, request: StandardRequest, planned_chat_id: str | None, reason: str) -> None: + log.warning( + "[SessionPlan] surface=%s reuse_chat_cancelled reason=%s session=%s planned_chat=%s account=%s", + getattr(request, 'surface', '-'), + reason, + _preview_identifier(getattr(request, 'session_key', None)), + _preview_identifier(planned_chat_id), + getattr(request, 'bound_account_email', None) or '-', + ) + + +def _assistant_tool_call_markup(message: dict[str, Any], client_profile: str) -> str: + tc_parts: list[str] = [] + for tc in message.get("tool_calls", []) or []: + fn = tc.get("function", {}) if isinstance(tc, dict) else {} + name = fn.get("name", "") + args_str = fn.get("arguments", "{}") + try: + args = json.loads(args_str) + except Exception: + args = {"raw": args_str} + tc_parts.append(_render_history_tool_call(name, args, client_profile)) + return "\n".join(part for part in tc_parts if part) + + +def render_session_message(message: dict[str, Any], *, client_profile: str, tools_enabled: bool) -> str: + role = message.get("role", "") + if role not in ("user", "assistant", "system", "tool"): + return "" + + if role == "tool": + tool_content = message.get("content", "") or "" + tool_call_id = str(message.get("tool_call_id", "") or "") + if isinstance(tool_content, list): + tool_content = "\n".join( + p.get("text", "") + for p in tool_content + if isinstance(p, dict) and p.get("type") == "text" + ) + elif not isinstance(tool_content, str): + tool_content = str(tool_content) + if not tool_content.strip(): + return "" + return f"[Tool Result]{(' id=' + tool_call_id) if tool_call_id else ''}\n{tool_content}\n[/Tool Result]" + + user_text_only = _extract_user_text_only(message.get("content", ""), client_profile=client_profile) if role == "user" else "" + text = _extract_text( + message.get("content", ""), + user_tool_mode=(tools_enabled and role == "user" and client_profile == CLAUDE_CODE_OPENAI_PROFILE), + client_profile=client_profile, + ) + + if role == "assistant" and not text and message.get("tool_calls"): + text = _assistant_tool_call_markup(message, client_profile) + + if not str(text or "").strip(): + return "" + + is_tool_result_only_user_msg = role == "user" and not user_text_only.strip() and bool(str(text).strip()) + prefix = "" if is_tool_result_only_user_msg else { + "user": "Human: ", + "assistant": "Assistant: ", + "system": "System: ", + }.get(role, "") + return text if is_tool_result_only_user_msg else f"{prefix}{text}" + + +def extract_session_history_entries(messages: list[dict[str, Any]], *, client_profile: str, tools_enabled: bool) -> list[SessionHistoryEntry]: + entries: list[SessionHistoryEntry] = [] + for message in messages or []: + rendered = render_session_message(message, client_profile=client_profile, tools_enabled=tools_enabled).strip() + if not rendered: + continue + digest = hashlib.sha256(rendered.encode("utf-8", errors="ignore")).hexdigest() + entries.append(SessionHistoryEntry(digest=digest, rendered=rendered)) + return entries + + +def build_continuation_prompt( + new_entries: list[SessionHistoryEntry], + *, + tool_names: list[str], + tools: list[dict] | None = None +) -> str: + """构建会话续接 prompt,包含精简工具定义以避免 Qwen 拦截""" + + # 构建精简工具定义 + if tools: + tool_lines = [] + for tool in tools: + name = tool.get("name", "") + if not name: + continue + + # 提取参数列表(最多显示 5 个) + params = tool.get("input_schema", {}).get("properties", {}) + param_keys = list(params.keys())[:5] + + if param_keys: + tool_lines.append(f"- {name}: {', '.join(param_keys)}") + else: + tool_lines.append(f"- {name}") + + tool_definitions = '\n'.join(tool_lines) if tool_lines else f"Available tools: {', '.join(tool_names[:12])}" + else: + # 降级:只显示工具名称(保持向后兼容) + tool_definitions = f"Available tools: {', '.join(tool_names[:12]) if tool_names else 'the available tools'}" + + lines = [ + '=== SAME TASK SESSION CONTINUATION ===', + 'This is the same ongoing task in the same upstream chat.', + 'Earlier context already exists in the conversation history of this chat.', + 'Process ONLY the new items below and continue the task from there.', + '', + 'CRITICAL TOOL CALL FORMAT - MUST USE ##TOOL_CALL## MARKERS:', + '##TOOL_CALL##', + '{"name": "EXACT_TOOL_NAME", "input": {"param": "value"}}', + '##END_CALL##', + '', + '=== AVAILABLE TOOLS ===', + tool_definitions, + '', + 'EXECUTION RULES:', + '- When you need to call a tool, output EXACTLY the ##TOOL_CALL##...##END_CALL## format above', + '- NO other format will work - pure JSON without markers will be INTERCEPTED', + '- If you just received a tool result, use it to continue the task immediately', + '- Do NOT call Agent, AskUserQuestion, EnterPlanMode, ExitPlanMode, EnterWorktree, ExitWorktree', + '- Do NOT ask questions or wait - execute the task directly', + '- Continue from where you left off based on the tool results', + '', + 'Do not repeat the same Read/Bash/WebSearch call if the result is already available in this chat.', + '', + 'NEW ITEMS:', + ] + + if new_entries: + lines.extend(entry.rendered for entry in new_entries) + else: + lines.append('No new client messages were appended. Continue from the current chat state and produce the next best response for the current task.') + + lines.extend(['', 'Assistant:']) + return '\n'.join(lines) + + +def build_retry_rebase_prompt(request: StandardRequest, *, reason: str | None = None) -> str: + base = (request.full_prompt or request.prompt or '').rstrip() + guidance = ( + '[MANDATORY NEXT STEP]: Continue this task from scratch using the tool contract exactly. ' + 'Do NOT repeat the previous malformed, redundant, or already-resolved step. ' + 'If the needed tool result is already in the provided history, use it and choose the next action or finish.' + ) + if reason: + if reason.startswith('repeated_same_tool:'): + tool_name = reason.split(':', 1)[1] or 'the same tool' + guidance = ( + f'[MANDATORY NEXT STEP]: You already called {tool_name} with the same input. ' + 'Do NOT repeat it. Use the existing result and move to the next relevant step or finish the task.' + ) + elif reason == 'unchanged_read_result': + guidance = ( + "[MANDATORY NEXT STEP]: You already received 'Unchanged since last read'. " + 'Do NOT call Read again on the same target. Use the current result and choose a different next action.' + ) + elif reason == 'search_no_results': + guidance = ( + '[MANDATORY NEXT STEP]: The last WebSearch returned no results. ' + 'Do NOT repeat the same search. Use another tool or answer with the best available information.' + ) + if base.endswith('Assistant:'): + return base[:-len('Assistant:')] + guidance + '\nAssistant:' + return base + '\n\n' + guidance + '\nAssistant:' + + +async def plan_persistent_session_turn(*, app, request: StandardRequest, payload: dict[str, Any], surface: str) -> PersistentSessionPlan: + full_prompt = request.prompt + entries = extract_session_history_entries( + payload.get('messages', []) or [], + client_profile=request.client_profile, + tools_enabled=bool(request.tools), + ) + current_hashes = [entry.digest for entry in entries] + + if not should_use_persistent_tool_session(request): + plan = PersistentSessionPlan( + enabled=False, + reuse_chat=False, + prompt=full_prompt, + full_prompt=full_prompt, + current_hashes=current_hashes, + existing_chat_id=None, + account_email=request.bound_account_email, + reason=persistent_session_disabled_reason(request), + existing_hash_count=0, + new_entries_count=len(entries), + ) + _log_session_plan(request=request, surface=surface, plan=plan) + return plan + + record = await app.state.session_affinity.get(request.session_key or '') + existing_hashes = list(record.message_hashes) if record else [] + existing_chat_id = record.chat_id if record else None + account_email = request.bound_account_email or (record.account_email if record else None) + + if not record or not existing_chat_id or not existing_hashes: + plan = PersistentSessionPlan( + enabled=True, + reuse_chat=False, + prompt=full_prompt, + full_prompt=full_prompt, + current_hashes=current_hashes, + existing_chat_id=None, + account_email=account_email, + reason='new_session', + existing_hash_count=len(existing_hashes), + new_entries_count=len(entries), + ) + _log_session_plan(request=request, surface=surface, plan=plan) + return plan + + if len(current_hashes) < len(existing_hashes) or current_hashes[:len(existing_hashes)] != existing_hashes: + plan = PersistentSessionPlan( + enabled=True, + reuse_chat=False, + prompt=full_prompt, + full_prompt=full_prompt, + current_hashes=current_hashes, + existing_chat_id=None, + account_email=account_email, + reason='history_desync', + existing_hash_count=len(existing_hashes), + new_entries_count=len(entries), + ) + _log_session_plan(request=request, surface=surface, plan=plan) + return plan + + new_entries = entries[len(existing_hashes):] + plan = PersistentSessionPlan( + enabled=True, + reuse_chat=True, + prompt=build_continuation_prompt( + new_entries, + tool_names=request.tool_names, + tools=request.tools + ), + full_prompt=full_prompt, + current_hashes=current_hashes, + existing_chat_id=existing_chat_id, + account_email=account_email, + reason='reuse_chat', + existing_hash_count=len(existing_hashes), + new_entries_count=len(new_entries), + ) + _log_session_plan(request=request, surface=surface, plan=plan) + return plan + + +def build_anthropic_assistant_history_message(*, execution, request: StandardRequest, directive) -> dict[str, Any]: + del request + content_blocks: list[dict[str, Any]] = [] + for block in directive.tool_blocks: + if block.get('type') == 'thinking': + continue + content_blocks.append(block) + if directive.stop_reason != 'tool_use' and execution.state.answer_text and not content_blocks: + content_blocks.append({"type": "text", "text": execution.state.answer_text}) + return {"role": "assistant", "content": content_blocks} + + +def build_openai_assistant_history_message(*, execution, request: StandardRequest, directive) -> dict[str, Any]: + del request + if directive.stop_reason == 'tool_use': + tool_calls = [ + { + 'id': block['id'], + 'type': 'function', + 'function': { + 'name': block['name'], + 'arguments': json.dumps(block.get('input', {}), ensure_ascii=False), + }, + } + for block in directive.tool_blocks + if block.get('type') == 'tool_use' + ] + return {'role': 'assistant', 'content': None, 'tool_calls': tool_calls} + return {'role': 'assistant', 'content': execution.state.answer_text} + + +def extend_hashes_with_assistant(*, current_hashes: list[str], assistant_message: dict[str, Any], request: StandardRequest) -> list[str]: + entries = extract_session_history_entries([assistant_message], client_profile=request.client_profile, tools_enabled=bool(request.tools)) + if not entries: + return list(current_hashes) + return list(current_hashes) + [entry.digest for entry in entries] + + +async def persist_session_turn(*, app, request: StandardRequest, surface: str, execution, assistant_message: dict[str, Any]) -> None: + if not getattr(request, 'persistent_session', False): + return + if not getattr(request, 'session_key', None): + return + if execution is None or not getattr(execution, 'chat_id', None) or getattr(execution, 'acc', None) is None: + return + ttl_seconds = app.state.context_offloader.settings.CONTEXT_ATTACHMENT_TTL_SECONDS + synced_hashes = extend_hashes_with_assistant( + current_hashes=getattr(request, 'session_message_hashes', []), + assistant_message=assistant_message, + request=request, + ) + bound_email = getattr(execution.acc, 'email', '') or getattr(request, 'bound_account_email', '') or '' + await app.state.session_affinity.bind_chat( + request.session_key, + surface=surface, + account_email=bound_email, + chat_id=execution.chat_id, + message_hashes=synced_hashes, + ttl_seconds=ttl_seconds, + ) + log.info( + "[SessionPlan] persisted surface=%s session=%s chat=%s hashes=%s account=%s", + surface, + _preview_identifier(request.session_key), + _preview_identifier(getattr(execution, 'chat_id', None)), + len(synced_hashes), + bound_email or '-', + ) + request.session_chat_invalidated = False + + +async def clear_invalidated_session_chat(*, app, request: StandardRequest) -> None: + if not getattr(request, 'session_chat_invalidated', False): + return + if not getattr(request, 'session_key', None): + return + await app.state.session_affinity.clear_chat(request.session_key) + log.warning( + "[SessionPlan] cleared_invalidated_chat surface=%s session=%s", + getattr(request, 'surface', '-'), + _preview_identifier(request.session_key), + ) + request.session_chat_invalidated = False diff --git a/backend/services/token_calc.py b/backend/services/token_calc.py new file mode 100644 index 0000000000000000000000000000000000000000..762a4b733dacad8de116715b0d4e006ceb1bc8e2 --- /dev/null +++ b/backend/services/token_calc.py @@ -0,0 +1,34 @@ +import tiktoken +import logging + +log = logging.getLogger("qwen2api.token") + +try: + # 默认使用 cl100k_base,因为目前这是最通用的 GPT-4 级分词器 + encoder = tiktoken.get_encoding("cl100k_base") +except Exception as e: + log.warning(f"Failed to load tiktoken: {e}") + encoder = None + +def count_tokens(text: str) -> int: + """计算文本的精确 Token 数""" + if not text: + return 0 + if encoder: + try: + return len(encoder.encode(text)) + except Exception: + pass + # Fallback:每汉字 1 token,每 3 个英文字母 1 token 的粗略估算 + return max(1, len(text.encode('utf-8')) // 2) + +def calculate_usage(prompt: str, completion: str) -> dict: + """结算:精确扣费""" + prompt_tokens = count_tokens(prompt) + completion_tokens = count_tokens(completion) + total_tokens = prompt_tokens + completion_tokens + return { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_tokens": total_tokens + } diff --git a/backend/services/tool_arg_fixer.py b/backend/services/tool_arg_fixer.py new file mode 100644 index 0000000000000000000000000000000000000000..29185cbe5c5397f1b51efab746b726c307e2beca --- /dev/null +++ b/backend/services/tool_arg_fixer.py @@ -0,0 +1,117 @@ +"""智能引号修复 + Edit/StrReplace 模糊匹配。 + +动机: + - AI 模型经常把普通 ASCII 引号写成中文/智能引号(" " ' '), + 导致 Edit 工具的 old_string 在文件中 exact match 不中直接失败。 + - old_string 中有微小格式差异(多空格、tab 变 space、反斜杠层级不同)也会 exact fail。 + +策略: + - replace_smart_quotes:把所有智能引号变成 ASCII 引号 + - repair_exact_match:old_string 不 exact match 时,构造 fuzzy 正则(容忍引号/空白/反斜杠) + 在文件里搜,如果唯一命中则替换 args 里的 old_string 为真实匹配文本 +""" + +from __future__ import annotations + +import os +import re +from typing import Any + + +_SMART_DOUBLE_QUOTES = {"\u00ab", "\u201c", "\u201d", "\u275e", "\u201f", "\u201e", "\u275d", "\u00bb"} +_SMART_SINGLE_QUOTES = {"\u2018", "\u2019", "\u201a", "\u201b"} + +_DOUBLE_QUOTE_CLASS = '["\u00ab\u201c\u201d\u275e\u201f\u201e\u275d\u00bb]' +_SINGLE_QUOTE_CLASS = "['\u2018\u2019\u201a\u201b]" + + +def replace_smart_quotes(text: str) -> str: + if not isinstance(text, str): + return text + out = [] + for ch in text: + if ch in _SMART_DOUBLE_QUOTES: + out.append('"') + elif ch in _SMART_SINGLE_QUOTES: + out.append("'") + else: + out.append(ch) + return "".join(out) + + +def _build_fuzzy_pattern(text: str) -> str: + parts = [] + for ch in text: + if ch in _SMART_DOUBLE_QUOTES or ch == '"': + parts.append(_DOUBLE_QUOTE_CLASS) + elif ch in _SMART_SINGLE_QUOTES or ch == "'": + parts.append(_SINGLE_QUOTE_CLASS) + elif ch in (" ", "\t"): + parts.append(r"\s+") + elif ch == "\\": + parts.append(r"\\{1,2}") + else: + parts.append(re.escape(ch)) + return "".join(parts) + + +def repair_exact_match(tool_name: str, args: dict[str, Any]) -> dict[str, Any]: + """对 Edit / StrReplace / search_replace 类工具:若 old_string 在文件里 exact + 不中,用 fuzzy pattern 搜;唯一命中则替换 args 里的 old_string 为精确匹配文本。""" + if not isinstance(args, dict): + return args + lower = (tool_name or "").lower() + if not any(key in lower for key in ("edit", "str_replace", "strreplace", "search_replace")): + return args + + old_string = args.get("old_string") or args.get("old_str") + if not isinstance(old_string, str) or not old_string: + return args + + file_path = args.get("file_path") or args.get("path") + if not isinstance(file_path, str) or not file_path: + return args + + try: + if not os.path.exists(file_path): + return args + with open(file_path, "r", encoding="utf-8", errors="replace") as f: + content = f.read() + except Exception: + return args + + if old_string in content: + # 即使 exact match,仍规范化 new_string 里的智能引号 + _normalize_new_string(args) + return args + + # fuzzy 搜 + try: + pattern = _build_fuzzy_pattern(old_string) + matches = list(re.finditer(pattern, content)) + except re.error: + return args + + if len(matches) != 1: + return args + + matched_text = matches[0].group(0) + if "old_string" in args: + args["old_string"] = matched_text + elif "old_str" in args: + args["old_str"] = matched_text + _normalize_new_string(args) + return args + + +def _normalize_new_string(args: dict[str, Any]) -> None: + for key in ("new_string", "new_str"): + if key in args and isinstance(args[key], str): + args[key] = replace_smart_quotes(args[key]) + + +def fix_tool_call_arguments(tool_name: str, args: dict[str, Any]) -> dict[str, Any]: + """对所有工具调用应用全部修复。幂等。""" + if not isinstance(args, dict): + return args + return repair_exact_match(tool_name, args) diff --git a/backend/services/tool_few_shot.py b/backend/services/tool_few_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b54f33a8f4e64040bf6e7b0f9ffdac7441c5a6 --- /dev/null +++ b/backend/services/tool_few_shot.py @@ -0,0 +1,191 @@ +"""Namespace-based few-shot injection:让模型学会调用所有类别的工具。 + +动机: + 当用户有 90+ 工具(含 MCP、Skills、Plugin 等多个命名空间),Qwen/上游只看 + prompt 里的指令列表时,经常只会调用几个它"熟悉"的核心工具(Read/Write/Bash), + MCP/Skills 类的第三方工具几乎不会被主动调用。 + 原因:模型倾向于**模仿 few-shot 里见过的调用**。如果历史里没有 MCP 工具的 + 调用示例,它就不会尝试 MCP 工具。 + +做法: + - 按命名空间把工具分组(mcp__playwright / mcp__memory / mcp__context7 / ...) + - 每个命名空间选一个代表工具(描述最长的那个) + - 构造一条合成的 [user→assistant] 对话,assistant 展示**多个不同类别**的工具 + 同时被调用(1 个核心工具 + 最多 4 个第三方代表) + - 这条合成对话插在真实用户请求之前 + +效果:模型看到"assistant 在第一步就用了 5 种不同类型的工具",会复现这种多样性。 +""" + +from __future__ import annotations + +import json +import re +from typing import Any + +# 核心工具名(Claude Code / Cursor / Codex 通用)——视为"基础能力" +_CORE_TOOL_PATTERNS = [ + re.compile(r"^(Read|read_file|ReadFile)$", re.IGNORECASE), + re.compile(r"^(Write|write_to_file|WriteFile|write_file)$", re.IGNORECASE), + re.compile(r"^(Bash|execute_command|RunCommand|run_command)$", re.IGNORECASE), + re.compile(r"^(ListDir|list_dir|list_directory|ListDirectory|list_files)$", re.IGNORECASE), + re.compile(r"^(Search|search_files|SearchFiles|grep_search|codebase_search|Grep|Glob)$", re.IGNORECASE), + re.compile(r"^(Edit|edit_file|EditFile|replace_in_file)$", re.IGNORECASE), + re.compile(r"^(attempt_completion|ask_followup_question|AskFollowupQuestion)$", re.IGNORECASE), +] + + +def _is_core_tool(name: str) -> bool: + return any(p.match(name) for p in _CORE_TOOL_PATTERNS) + + +def _tool_namespace(name: str) -> str: + """推断工具的命名空间,用于分组。""" + if not name: + return "" + # mcp__playwright__click → mcp__playwright + m = re.match(r"^(mcp__[^_]+)", name) + if m: + return m.group(1) + # foo__bar__baz → foo + m = re.match(r"^([^_]+)__", name) + if m: + return m.group(1) + # snake_case:以首段为 namespace(前提至少 3 段,避免 "read_file" 被归为 "read") + parts = name.split("_") + if len(parts) >= 3: + return parts[0] + # camelCase:取首段驼峰 + m = re.match(r"^([A-Z][a-z]+(?:[A-Z][a-z]+)?)", name) + if m and m.group(1) != name: + return m.group(1) + return name + + +def _example_params_for_core(name: str) -> dict[str, Any]: + low = name.lower() + if any(p.match(name) for p in [_CORE_TOOL_PATTERNS[0]]): # Read + return {"file_path": "src/index.ts"} + if any(p.match(name) for p in [_CORE_TOOL_PATTERNS[1]]): # Write + return {"file_path": "output.txt", "content": "..."} + if any(p.match(name) for p in [_CORE_TOOL_PATTERNS[2]]): # Bash + return {"command": "ls -la"} + if any(p.match(name) for p in [_CORE_TOOL_PATTERNS[3]]): # ListDir + return {"path": "."} + if any(p.match(name) for p in [_CORE_TOOL_PATTERNS[4]]): # Search / Grep / Glob + if "glob" in low: + return {"pattern": "**/*.py"} + return {"pattern": "TODO"} + if any(p.match(name) for p in [_CORE_TOOL_PATTERNS[5]]): # Edit + return {"file_path": "src/main.ts", "old_string": "old", "new_string": "new"} + return {"input": "value"} + + +def _example_params_from_schema(tool: dict[str, Any]) -> dict[str, Any]: + """从工具 schema 提取前 2 个参数作为示例。""" + schema = tool.get("parameters") or tool.get("input_schema") or {} + props = schema.get("properties") if isinstance(schema, dict) else None + if not isinstance(props, dict): + return {"input": "value"} + out: dict[str, Any] = {} + for key, spec in list(props.items())[:2]: + if not isinstance(spec, dict): + out[key] = "value" + continue + t = spec.get("type", "string") + if t == "boolean": + out[key] = True + elif t in ("number", "integer"): + out[key] = 1 + elif t == "array": + out[key] = [] + elif t == "object": + out[key] = {} + else: + out[key] = "value" + return out or {"input": "value"} + + +def pick_few_shot_tools(tools: list[dict[str, Any]], max_third_party: int = 4) -> list[dict[str, Any]]: + """从工具列表选出 few-shot 代表集: + - 1 个核心工具(优先 Read,次之 Bash,再次之任意核心工具) + - 最多 max_third_party 个第三方工具代表(按命名空间分组,每组选描述最长) + """ + if not tools: + return [] + + core_tools = [t for t in tools if _is_core_tool(t.get("name", ""))] + third_party = [t for t in tools if not _is_core_tool(t.get("name", ""))] + + chosen: list[dict[str, Any]] = [] + + # 1) 核心代表 + def _find(pattern: re.Pattern) -> dict[str, Any] | None: + return next((t for t in tools if pattern.match(t.get("name", ""))), None) + + core_pick = _find(_CORE_TOOL_PATTERNS[0]) or _find(_CORE_TOOL_PATTERNS[2]) + if core_pick is None and core_tools: + core_pick = core_tools[0] + if core_pick is not None: + chosen.append(core_pick) + + # 2) 第三方按 namespace 分组 + groups: dict[str, list[dict[str, Any]]] = {} + for t in third_party: + ns = _tool_namespace(t.get("name", "")) + groups.setdefault(ns, []).append(t) + + # 命名空间按工具数量降序;每个空间取描述最长的一个作代表 + for ns, items in sorted(groups.items(), key=lambda kv: -len(kv[1])): + if len(chosen) >= 1 + max_third_party: + break + rep = max(items, key=lambda x: len(x.get("description", "") or "")) + chosen.append(rep) + + # 还是空就退化为第一个工具 + if not chosen and tools: + chosen.append(tools[0]) + + return chosen + + +def build_example_params(tool: dict[str, Any]) -> dict[str, Any]: + """对任意工具构造一个合理的 input 示例。""" + name = tool.get("name", "") + if _is_core_tool(name): + return _example_params_for_core(name) + return _example_params_from_schema(tool) + + +def render_few_shot_turn( + few_shot_tools: list[dict[str, Any]], + render_tool_call, + thinking_enabled: bool = False, +) -> tuple[str, str]: + """渲染合成的 [user, assistant] 对话。返回 (user_text, assistant_text)。 + + render_tool_call(name, input) -> str: 使用调用方的工具调用渲染函数 + (通常是 ##TOOL_CALL##\n{json}\n##END_CALL##)。 + """ + actions = [render_tool_call(t.get("name", ""), build_example_params(t)) for t in few_shot_tools] + user_text = ( + "[FEW-SHOT WARM-UP] Now show me how you would emit multiple action markers in a single " + "response. Use representatives from different action categories — including MCP/plugin " + "actions if available — to demonstrate you can invoke any of them, not just core ones." + ) + body = "\n\n".join(actions) + if thinking_enabled: + thinking = ( + "\n" + "The user wants me to demonstrate multi-action capability. I should emit markers " + "for representatives from each action category (core + MCP/plugin) in one turn.\n" + "\n\n" + ) + assistant_text = f"{thinking}Here are examples across action categories:\n\n{body}" + else: + assistant_text = f"Understood. Here are example markers across action categories:\n\n{body}" + return user_text, assistant_text + + +def tool_summary_for_log(few_shot_tools: list[dict[str, Any]]) -> str: + return ", ".join(t.get("name", "?") for t in few_shot_tools) diff --git a/backend/services/tool_name_obfuscation.py b/backend/services/tool_name_obfuscation.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ac38aa89ebd0f21801e98d82bd9a295ae3fdcb --- /dev/null +++ b/backend/services/tool_name_obfuscation.py @@ -0,0 +1,81 @@ +"""工具名混淆:让 Claude Code 的 **全部** 工具名都与 Qwen 内置函数命名空间隔离, +避免 Qwen 上游把客户端工具名当内置函数名校验并返回 "Tool X does not exists." 拦截。 + +策略(两层): +1. **显式别名**(高价值、常被拦截的短名):Read→fs_open_file 等 +2. **通用兜底**:其余所有工具自动加 `u_` 前缀,如 TaskCreate→u_TaskCreate + mcp__playwright__click→u_mcp__playwright__click 等。 + `u_` 前缀保证名字空间不会与 Qwen 内置函数碰撞。 + +出站(发往 Qwen):客户端名 → 别名 / u_前缀名 +入站(Qwen 返回):别名 / u_前缀名 → 客户端名 +""" + +from __future__ import annotations + +import re + +# 高价值显式别名:这些短名最容易被 Qwen 内置函数命中,用完全独立的 snake_case。 +TOOL_NAME_ALIASES: dict[str, str] = { + "Read": "fs_open_file", + "Write": "fs_put_file", + "Edit": "fs_patch_file", + "Bash": "shell_run", + "Grep": "text_search", + "Glob": "path_find", + "NotebookEdit": "notebook_patch", + "WebFetch": "http_get_url", + "WebSearch": "web_query", +} + +REVERSE_ALIASES: dict[str, str] = {v: k for k, v in TOOL_NAME_ALIASES.items()} + +# 所有未显式别名的工具自动加这个前缀,保证别名空间与 Qwen 内置隔离。 +# 选 "u_" (user tool) 短、没语义、绝不可能和任何 Qwen 内置函数名冲突。 +_AUTO_PREFIX = "u_" + + +def to_qwen_name(name: str) -> str: + """出站:客户端工具名 → Qwen-safe 别名。 + - 有显式别名:用别名(如 Read → fs_open_file) + - 无显式别名:加 u_ 前缀(如 TaskCreate → u_TaskCreate) + - 空值:原样返回 + """ + if not isinstance(name, str) or not name: + return name + if name in TOOL_NAME_ALIASES: + return TOOL_NAME_ALIASES[name] + # 已经是 Qwen-safe 别名(回调场景避免双重前缀) + if name in REVERSE_ALIASES or name.startswith(_AUTO_PREFIX): + return name + return _AUTO_PREFIX + name + + +def from_qwen_name(name: str) -> str: + """入站:Qwen 返回的别名 → 客户端原名。 + - 命中显式反向表:映射回原名(fs_open_file → Read) + - 命中 u_ 前缀:剥掉前缀(u_TaskCreate → TaskCreate) + - 未识别:原样返回(兼容 Qwen 偶尔直接返回原名的情况) + """ + if not isinstance(name, str) or not name: + return name + if name in REVERSE_ALIASES: + return REVERSE_ALIASES[name] + if name.startswith(_AUTO_PREFIX): + return name[len(_AUTO_PREFIX):] + return name + + +# 用于替换 prompt 中的裸工具名引用(如 "Read/Edit/Write"、"call Read")。 +# 只处理有显式别名的那些(其他名字像 TaskCreate 很少在自由文本里裸出现)。 +# 按长度降序避免短名被先匹配。 +_BARE_NAME_PATTERN = re.compile( + r"\b(" + "|".join(sorted(TOOL_NAME_ALIASES.keys(), key=len, reverse=True)) + r")\b" +) + + +def obfuscate_bare_names(text: str) -> str: + """把 prompt 文本里裸出现的工具名(如指令块里的 "Read/Edit/Write")替换成别名。""" + if not text: + return text + return _BARE_NAME_PATTERN.sub(lambda m: TOOL_NAME_ALIASES[m.group(1)], text) diff --git a/backend/services/tool_parser.py b/backend/services/tool_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f34a270fef9f79039b7fab4b8d5ada7a901db6c0 --- /dev/null +++ b/backend/services/tool_parser.py @@ -0,0 +1,623 @@ +import json +import logging +import re +import uuid +from typing import Any, cast + +from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE, OPENCLAW_OPENAI_PROFILE +from backend.core.request_logging import get_request_context +from backend.services.tool_arg_fixer import fix_tool_call_arguments +from backend.services.tool_name_obfuscation import from_qwen_name +from backend.toolcall.normalize import build_tool_name_registry, normalize_tool_name +from backend.toolcall.parser import parse_tool_calls_detailed + +__all__ = ["parse_tool_calls", "parse_tool_calls_detailed", "inject_format_reminder", "parse_tool_calls_silent", "ToolSieve"] + +log = logging.getLogger("qwen2api.tool_parser") + + +CASE_SENSITIVE_TOOL_NAMES = {"Bash", "Edit", "Write", "Read", "Grep", "Glob", "WebFetch", "WebSearch"} + + +def _normalize_tool_name_case(name: str, tool_names: set[str]) -> str: + if not isinstance(name, str) or not name: + return name + if name in tool_names: + return name + lowered = name.lower() + for candidate in tool_names: + if candidate.lower() == lowered: + if candidate in CASE_SENSITIVE_TOOL_NAMES: + return candidate + return candidate + return name + + +def _find_tool_use_json(text: str, tool_names: set[str]): + i = 0 + while i < len(text): + pos = text.find('{', i) + if pos == -1: + break + depth = 0 + for j in range(pos, len(text)): + if text[j] == '{': + depth += 1 + elif text[j] == '}': + depth -= 1 + if depth == 0: + candidate = text[pos:j + 1] + try: + obj = json.loads(candidate) + if isinstance(obj, dict) and obj.get("type") == "tool_use" and obj.get("name"): + normalized_name = normalize_tool_name(obj.get("name", ""), tool_names) + if normalized_name in tool_names: + obj = dict(obj) + obj["name"] = normalized_name + return pos, obj + + except (json.JSONDecodeError, ValueError): + pass + break + i = pos + 1 + + return None + + +def _extract_first_xml_tool_call(text: str) -> str | None: + wrapped_match = re.search(r"\s*([\s\S]*?)\s*", text, re.IGNORECASE) + if wrapped_match: + return wrapped_match.group(1) + + tool_call_match = re.search(r"\s*(\{[\s\S]*?\}|[\s\S]*?)\s*", text, re.IGNORECASE) + if tool_call_match: + return tool_call_match.group(0) + return None + + +def _extract_first_json_tool_call(text: str) -> str | None: + normalized = text.strip() + + # 优先查找完整的 JSON 对象 + # markers 按优先级:Qwen 官方 tool_calls 外层包装 > 单对象 > 松散片段 + markers = [ + '{"name"', + '{"name"', + '{"tool_calls"', + '{"name"', + '"name":', + '"name="', + 'function.name:', + ] + start_positions = [normalized.find(marker) for marker in markers if normalized.find(marker) != -1] + if not start_positions: + return None + start = min(start_positions) + candidate = normalized[start:] + + wrapped_match = re.search(r"\s*([\s\S]*?)\s*", candidate, re.IGNORECASE) + if wrapped_match: + return wrapped_match.group(1) + + tool_call_match = re.search(r"\s*(\{[\s\S]*?\}|[\s\S]*?)\s*", candidate, re.IGNORECASE) + if tool_call_match: + return tool_call_match.group(0) + + json_start = candidate.find("{") + if json_start == -1: + return None + depth = 0 + for idx in range(json_start, len(candidate)): + ch = candidate[idx] + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + json_str = candidate[json_start:idx + 1] + # 验证是否是有效的工具调用 JSON + try: + obj = json.loads(json_str) + if isinstance(obj, dict) and "name" in obj: + return json_str + except (json.JSONDecodeError, ValueError): + pass + return json_str + return candidate[json_start:] + + +def _normalize_fragmented_tool_call(answer: str) -> str: + text = answer.strip() + if "##TOOL_CALL##" in text and "##END_CALL##" in text: + return text + + extracted_tool_call = _extract_first_xml_tool_call(text) or _extract_first_json_tool_call(text) + if extracted_tool_call: + return extracted_tool_call + + text = re.sub(r"[\s\S]*?", "", text, flags=re.IGNORECASE) + text = re.sub(r"", "", text, flags=re.IGNORECASE) + text = re.sub(r"Tool\s+[A-Za-z0-9_.:-]*\s*does not exists?\\.?", "", text, flags=re.IGNORECASE) + text = re.sub(r"```[\s\S]*?```", "", text) + + extracted_tool_call = _extract_first_xml_tool_call(text) or _extract_first_json_tool_call(text) + if extracted_tool_call: + return extracted_tool_call + + lines = [] + for raw_line in text.splitlines(): + line = raw_line.strip() + if not line: + continue + line = re.sub(r"^[•●·\-*]+\s*", "", line) + line = line.replace("END_CALL##", "##END_CALL##") + if line: + lines.append(line) + + normalized = "\n".join(lines) + if "TOOL_CALL##" in normalized and "##TOOL_CALL##" not in normalized: + normalized = normalized.replace("TOOL_CALL##", "##TOOL_CALL##") + if "##END_CALL##" in normalized and "##TOOL_CALL##" not in normalized and '"name"' in normalized: + normalized = f"##TOOL_CALL##\n{normalized}" + return normalized + + +def _coerce_tool_input(name: str, input_data: Any, tools: list[dict[str, Any]]) -> Any: + if not isinstance(input_data, dict): + return input_data + + # 修正 AskUserQuestion 工具参数 + if name == "AskUserQuestion": + fixed = dict(input_data) + + # 如果只有 question 字段,转换为 questions 数组 + if "question" in fixed and "questions" not in fixed: + question_text = fixed.pop("question") + fixed["questions"] = [{ + "question": question_text, + "header": "Question", + "options": [ + {"label": "Yes", "description": "Confirm"}, + {"label": "No", "description": "Decline"} + ], + "multiSelect": False + }] + log.info(f"[ToolCoerce] Fixed AskUserQuestion: converted 'question' to 'questions' array") + + # 确保 questions 是数组 + if "questions" in fixed: + if not isinstance(fixed["questions"], list): + fixed["questions"] = [fixed["questions"]] + + # 验证每个问题的格式 + for i, q in enumerate(fixed["questions"]): + if not isinstance(q, dict): + continue + + # 确保有必需字段 + if "question" not in q: + q["question"] = "Please provide your input" + if "header" not in q: + q["header"] = "Question" + if "multiSelect" not in q: + q["multiSelect"] = False + + # 确保 options 格式正确 + if "options" not in q: + q["options"] = [ + {"label": "Continue", "description": "Proceed"}, + {"label": "Cancel", "description": "Stop"} + ] + elif isinstance(q.get("options"), list): + for j, opt in enumerate(q["options"]): + if isinstance(opt, str): + q["options"][j] = {"label": opt, "description": opt} + elif isinstance(opt, dict): + if "label" not in opt: + opt["label"] = opt.get("description", f"Option {j+1}") + if "description" not in opt: + opt["description"] = opt.get("label", "") + + return fixed + + # 修正 Agent 工具参数 + if name == "Agent": + fixed = dict(input_data) + if "description" not in fixed: + fixed["description"] = "Execute sub-task" + if "prompt" not in fixed: + fixed["prompt"] = fixed.get("description", "Execute the task") + return fixed + + # 修正 Read 工具参数 + if name == "Read": + fixed = dict(input_data) + if "file_path" not in fixed: + if "path" in fixed: + fixed["file_path"] = fixed.pop("path") + elif "filename" in fixed: + fixed["file_path"] = fixed.pop("filename") + return fixed + + # 修正 Bash 工具参数 + if name == "Bash": + fixed = dict(input_data) + if "command" not in fixed: + if "cmd" in fixed: + fixed["command"] = fixed.pop("cmd") + elif "script" in fixed: + fixed["command"] = fixed.pop("script") + return fixed + + # 原有的 query/queries 转换逻辑 + query_value = input_data.get("query") + queries = input_data.get("queries") + if query_value or "queries" not in input_data: + return input_data + if not any(isinstance(tool, dict) and isinstance(tool.get("parameters"), dict) and isinstance(tool["parameters"].get("properties"), dict) and "query" in tool["parameters"]["properties"] for tool in tools): + return input_data + + if isinstance(queries, list): + merged = "\n".join(str(item).strip() for item in queries if str(item).strip()) + if merged: + coerced = dict(input_data) + coerced.pop("queries", None) + coerced["query"] = merged + return coerced + if isinstance(queries, str) and queries.strip(): + coerced = dict(input_data) + coerced.pop("queries", None) + coerced["query"] = queries.strip() + return coerced + + return input_data + + +def parse_tool_calls(answer: str, tools: list): + return _parse_tool_calls(answer, tools, emit_logs=True) + + +def parse_tool_calls_silent(answer: str, tools: list): + return _parse_tool_calls(answer, tools, emit_logs=False) + + +def _parse_tool_calls(answer: str, tools: list, *, emit_logs: bool): + answer = _normalize_fragmented_tool_call(answer) + ctx = get_request_context() + req_tag = f"req={ctx.get('req_id', '-')} chat={ctx.get('chat_id', '-')}" + if not tools: + return [{"type": "text", "text": answer}], "end_turn" + tool_names = {t.get("name") for t in tools if t.get("name")} + tool_registry = build_tool_name_registry(tool_names) + + def _log_debug(message: str) -> None: + if emit_logs: + log.debug(message) + + def _log_info(message: str) -> None: + if emit_logs: + log.info(message) + + def _log_warning(message: str) -> None: + if emit_logs: + log.warning(message) + + # 强制记录原始输入用于调试(但遵守 emit_logs 开关:ToolSieve 流式解析每 chunk 都调一次, + # 若无条件记录会刷 1000+ 行 [ToolParse]——只在 finalize/诊断场景打印) + if emit_logs: + log.info(f"[ToolParse] [{req_tag}] 原始回复({len(answer)}字): {answer[:500]!r}") + + def _make_tool_block(name, input_data, prefix=""): + # 入站反混淆:Qwen 返回的别名(ReadX)→ 客户端原名(Read)。 + # 未知别名原样返回,不影响 Qwen 直接返回原名的兼容路径。 + name = from_qwen_name(name) + normalized_name = normalize_tool_name(name, tool_registry.values()) + cased_name = _normalize_tool_name_case(normalized_name, tool_names) + if cased_name not in tool_names: + _log_warning(f"[ToolParse] 工具名不匹配,回退为普通文本: name={name!r}, normalized={normalized_name!r}, cased={cased_name!r}, tools={tool_names}") + return [{"type": "text", "text": answer}], "end_turn" + coerced_input = _coerce_tool_input(cased_name, input_data, tools) + # 智能引号修复 + Edit/StrReplace 的 old_string fuzzy 修复 + coerced_input = fix_tool_call_arguments(cased_name, coerced_input) + tool_id = f"toolu_{uuid.uuid4().hex[:8]}" + blocks = [] + if prefix: + blocks.append({"type": "text", "text": prefix}) + blocks.append({"type": "tool_use", "id": tool_id, "name": cased_name, "input": coerced_input}) + _log_info(f"[ToolParse] 返回工具块: original={name!r}, normalized={normalized_name!r}, final={cased_name!r}, input={json.dumps(coerced_input, ensure_ascii=False)[:200]}") + return blocks, "tool_use" + + detailed = parse_tool_calls_detailed(answer, tool_names) + detailed_calls = cast(list[dict[str, Any]], detailed["calls"]) + if detailed_calls: + first_call = detailed_calls[0] + _log_info(f"[ToolParse] ✓ 详细解析格式: source={detailed['source']}, name={first_call['name']!r}, input={json.dumps(first_call['input'], ensure_ascii=False)[:200]}") + return _make_tool_block(first_call["name"], first_call["input"]) + + tc_m = re.search(r'##TOOL_CALL##\s*(.*?)\s*##END_CALL##', answer, re.DOTALL | re.IGNORECASE) + if tc_m: + try: + obj = json.loads(tc_m.group(1)) + name = obj.get("name", "") + inp = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {})))) + if isinstance(inp, str): + try: + inp = json.loads(inp) + except Exception: + inp = {"value": inp} + prefix = answer[:tc_m.start()].strip() + _log_info(f"[ToolParse] ✓ ##TOOL_CALL## 格式: name={name!r}, input={str(inp)[:120]}") + return _make_tool_block(name, inp, prefix) + except (json.JSONDecodeError, ValueError) as e: + _log_warning(f"[ToolParse] ##TOOL_CALL## 格式解析失败: {e}, content={tc_m.group(1)[:100]!r}") + + xml_m = re.search(r'\s*(.*?)\s*', answer, re.DOTALL | re.IGNORECASE) + if xml_m: + try: + obj = json.loads(xml_m.group(1)) + name = obj.get("name", "") + inp = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {})))) + if isinstance(inp, str): + try: + inp = json.loads(inp) + except Exception: + inp = {"value": inp} + prefix = answer[:xml_m.start()].strip() + _log_info(f"[ToolParse] ✓ XML格式 : name={name!r}, input={str(inp)[:120]}") + return _make_tool_block(name, inp, prefix) + except (json.JSONDecodeError, ValueError) as e: + _log_warning(f"[ToolParse] XML格式解析失败: {e}, content={xml_m.group(1)[:100]!r}") + + cb_m = re.search(r'```tool_call\s*\n(.*?)\n```', answer, re.DOTALL) + if cb_m: + try: + obj = json.loads(cb_m.group(1).strip()) + name = obj.get("name", "") + inp = obj.get("input", obj.get("args", {})) + if isinstance(inp, str): + try: + inp = json.loads(inp) + except Exception: + inp = {"value": inp} + prefix = answer[:cb_m.start()].strip() + _log_info(f"[ToolParse] ✓ 代码块格式 tool_call: name={name!r}, input={str(inp)[:120]}") + return _make_tool_block(name, inp, prefix) + except (json.JSONDecodeError, ValueError) as e: + _log_warning(f"[ToolParse] 代码块格式解析失败: {e}") + + stripped = re.sub(r'```json\s*\n?', '', answer) + stripped = re.sub(r'\n?```', '', stripped) + result = _find_tool_use_json(stripped, tool_names) + if result: + pos, tool_call = result + prefix = stripped[:pos].strip() + tool_id = tool_call.get("id") or f"toolu_{uuid.uuid4().hex[:8]}" + _log_info(f"[ToolParse] ✓ 旧JSON格式 tool_call: name={tool_call['name']!r}") + blocks = [] + if prefix: + blocks.append({"type": "text", "text": prefix}) + blocks.append({ + "type": "tool_use", + "id": tool_id, + "name": tool_call["name"], + "input": _coerce_tool_input(tool_call["name"], tool_call.get("input", {}), tools), + }) + return blocks, "tool_use" + + # 尝试解析纯 JSON 格式: {"name": "...", "input": {...}} + stripped_clean = stripped.strip() + try: + if stripped_clean.startswith('{') and stripped_clean.endswith('}'): + obj = json.loads(stripped_clean) + if isinstance(obj, dict) and "name" in obj: + name = obj.get("name", "") + inp = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {})))) + if isinstance(inp, str): + try: + inp = json.loads(inp) + except Exception: + inp = {"value": inp} + _log_info(f"[ToolParse] ✓ 纯JSON格式: name={name!r}, input={str(inp)[:120]}") + return _make_tool_block(name, inp) + except (json.JSONDecodeError, ValueError) as e: + _log_debug(f"[ToolParse] 纯JSON格式解析失败: {e}, content={stripped_clean[:200]!r}") + + _log_warning(f"[ToolParse] ✗ 未检测到工具调用,作为普通文本返回。工具列表: {tool_names}") + return [{"type": "text", "text": answer}], "end_turn" + + +class ToolSieve: + """工具调用流式检测器 - 实时检测并分离工具调用""" + + def __init__(self, tool_names: list[str]): + self.tool_names = set(tool_names) if tool_names else set() + self.pending = "" + self.capture = "" + self.capturing = False + self.pending_tool_calls = [] + self.tool_calls_detected = False + + def process_chunk(self, chunk: str) -> list[dict]: + """ + 处理一个chunk,返回事件列表 + 事件类型: + - {"type": "content", "text": "..."} # 普通文本 + - {"type": "tool_calls", "calls": [...]} # 工具调用 + """ + if not chunk: + return [] + + self.pending += chunk + events = [] + + # 如果正在捕获工具调用 + if self.capturing: + self.capture += self.pending + self.pending = "" + + # 尝试解析 + prefix, calls, suffix, ready = self._consume_tool_capture() + + if ready and calls: + # 解析成功 + if prefix: + events.append({"type": "content", "text": prefix}) + + self.pending_tool_calls = calls + self.tool_calls_detected = True + self.pending = suffix + self.capture = "" + self.capturing = False + + return events + + # 检测工具调用开始 + start = self._find_tool_start(self.pending) + + if start >= 0: + # 找到工具调用开始 + prefix = self.pending[:start] + if prefix: + events.append({"type": "content", "text": prefix}) + + self.capture = self.pending[start:] + self.pending = "" + self.capturing = True + else: + # 没找到,输出安全部分 + safe, hold = self._split_safe_content(self.pending) + if safe: + events.append({"type": "content", "text": safe}) + self.pending = hold + + return events + + def _find_tool_start(self, text: str) -> int: + """查找工具调用开始位置""" + markers = [ + '{"tool_calls"', + '{"name":', + '', + '##TOOL_CALL##', + 'function.name:', + ] + + positions = [] + for marker in markers: + pos = text.find(marker) + if pos >= 0: + positions.append(pos) + + return min(positions) if positions else -1 + + def _consume_tool_capture(self) -> tuple[str, list, str, bool]: + """尝试解析捕获的工具调用""" + if not self.capture: + return "", [], "", False + + # 尝试解析工具调用 + try: + # 使用现有的解析逻辑 + blocks, stop_reason = parse_tool_calls_silent(self.capture, + [{"name": name} for name in self.tool_names]) + + if stop_reason == "tool_use": + # 找到工具��用 + tool_blocks = [b for b in blocks if b.get("type") == "tool_use"] + if tool_blocks: + # 转换为标准格式 + calls = [{ + "name": tb["name"], + "input": tb["input"] + } for tb in tool_blocks] + + # 提取前缀文本 + text_blocks = [b for b in blocks if b.get("type") == "text"] + prefix = text_blocks[0]["text"] if text_blocks else "" + + return prefix, calls, "", True + except Exception as e: + log.debug(f"[ToolSieve] 解析失败: {e}") + + # 还不完整或解析失败 + return "", [], "", False + + def _split_safe_content(self, text: str) -> tuple[str, str]: + """分离安全内容和需要保留的部分""" + # 保留最后几个字符,防止工具调用标记被截断 + if len(text) < 20: + return "", text + + return text[:-10], text[-10:] + + def flush(self) -> list[dict]: + """刷新剩余内容""" + events = [] + + if self.pending_tool_calls: + events.append({"type": "tool_calls", "calls": self.pending_tool_calls}) + self.pending_tool_calls = [] + + if self.capturing and self.capture: + # 尝试最后一次解析 + prefix, calls, suffix, ready = self._consume_tool_capture() + if ready and calls: + if prefix: + events.append({"type": "content", "text": prefix}) + events.append({"type": "tool_calls", "calls": calls}) + self.tool_calls_detected = True + if suffix: + events.append({"type": "content", "text": suffix}) + else: + # 解析失败,检查是否看起来像工具调用 + if not self._looks_like_incomplete_tool_call(self.capture): + events.append({"type": "content", "text": self.capture}) + + if self.pending: + events.append({"type": "content", "text": self.pending}) + + return events + + def _looks_like_incomplete_tool_call(self, text: str) -> bool: + """检查文本是否看起来像不完整的工具调用""" + markers = ['{"tool_calls"', '{"name":', '', '##TOOL_CALL##', 'function.name:'] + return any(marker in text for marker in markers) + + def has_tool_calls(self) -> bool: + """是否检测到工具调用""" + return self.tool_calls_detected or bool(self.pending_tool_calls) + + +def inject_format_reminder(prompt: str, tool_name: str, *, client_profile: str = OPENCLAW_OPENAI_PROFILE) -> str: + """Inject a format correction reminder into the prompt before the final 'Assistant:' tag. + Used when upstream produced the toxic 'Tool X does not exists.' hallucination — + the reminder teaches the model to emit the text-marker format without that phrase.""" + if client_profile == CLAUDE_CODE_OPENAI_PROFILE: + reminder = ( + "[CORRECTION / 纠正]: Your previous output contained a forbidden hallucinated error phrase.\n" + f"要调用 {tool_name},只输出这个精确格式,不要有其他文本:\n" + f"To invoke {tool_name}, output ONLY this exact format with NO other text:\n" + "##TOOL_CALL##\n" + f'{{"name": "{tool_name}", "input": {{"arg1": "value1", "arg2": "value2"}}}}\n' + "##END_CALL##\n\n" + "ABSOLUTELY FORBIDDEN in your next output:\n" + "- Any disclaimer about a tool being unavailable, missing, or unregistered\n" + "- Any sentence claiming you are unable to run a function\n" + "- Any apology for failing to invoke something\n" + "These ##TOOL_CALL## blocks are plain TEXT MARKERS the proxy parses — not native function calls.\n" + ) + else: + reminder = ( + "[CORRECTION / 纠正]: 请用正确的 ##TOOL_CALL## 格式重新发起调用。\n" + "You MUST use ##TOOL_CALL## format and NOTHING ELSE:\n" + "##TOOL_CALL##\n" + f'{{"name": {json.dumps(tool_name)}, "input": {{...your args here...}}}}\n' + "##END_CALL##\n" + "不要输出任何声称无法执行工具的话。The ##TOOL_CALL## blocks are TEXT MARKERS, not native functions.\n" + ) + prompt = prompt.rstrip() + if prompt.endswith("Assistant:"): + return prompt[: -len("Assistant:")] + reminder + "\nAssistant:" + return prompt + "\n\n" + reminder + "\nAssistant:" + + diff --git a/backend/services/tool_validator.py b/backend/services/tool_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..f5aec61386bad7c02c63d5ee20036c61c3834e60 --- /dev/null +++ b/backend/services/tool_validator.py @@ -0,0 +1,180 @@ +""" +工具参数验证和修正模块 +确保通义千问生成的工具调用参数符合 Claude Code 的要求 +""" +import logging +from typing import Any + +log = logging.getLogger("qwen2api.tool_validator") + + +def validate_and_fix_tool_call(tool_name: str, tool_input: dict) -> dict: + """ + 验证并修正工具调用参数 + + Args: + tool_name: 工具名称 + tool_input: 工具输入参数 + + Returns: + 修正后的工具输入参数 + """ + if tool_name == "AskUserQuestion": + return _fix_ask_user_question(tool_input) + elif tool_name == "Agent": + return _fix_agent(tool_input) + elif tool_name == "Read": + return _fix_read(tool_input) + elif tool_name == "Bash": + return _fix_bash(tool_input) + else: + return tool_input + + +def _fix_ask_user_question(tool_input: dict) -> dict: + """ + 修正 AskUserQuestion 工具参数 + + Claude Code 期望的格式: + { + "questions": [ + { + "question": "...", + "header": "...", + "options": [ + {"label": "...", "description": "..."}, + ... + ], + "multiSelect": false + } + ] + } + """ + fixed = dict(tool_input) + + # 如果只有 question 字段,转换为 questions 数组 + if "question" in fixed and "questions" not in fixed: + question_text = fixed.pop("question") + fixed["questions"] = [{ + "question": question_text, + "header": "Question", + "options": [ + {"label": "Yes", "description": "Confirm"}, + {"label": "No", "description": "Decline"} + ], + "multiSelect": False + }] + log.info(f"[ToolValidator] Fixed AskUserQuestion: converted 'question' to 'questions' array") + + # 确保 questions 是数组 + if "questions" in fixed: + if not isinstance(fixed["questions"], list): + fixed["questions"] = [fixed["questions"]] + + # 验证每个问题的格式 + for i, q in enumerate(fixed["questions"]): + if not isinstance(q, dict): + continue + + # 确保有 question 字段 + if "question" not in q: + q["question"] = "Please provide your input" + + # 确保有 header 字段 + if "header" not in q: + q["header"] = "Question" + + # 确保有 options 字段 + if "options" not in q: + q["options"] = [ + {"label": "Continue", "description": "Proceed with the task"}, + {"label": "Cancel", "description": "Stop the task"} + ] + + # 确保 options 格式正确 + if isinstance(q.get("options"), list): + for j, opt in enumerate(q["options"]): + if isinstance(opt, str): + # 如果 option 是字符串,转换为对象 + q["options"][j] = { + "label": opt, + "description": opt + } + elif isinstance(opt, dict): + # 确保有 label 和 description + if "label" not in opt: + opt["label"] = opt.get("description", f"Option {j+1}") + if "description" not in opt: + opt["description"] = opt.get("label", "") + + # 确保有 multiSelect 字段 + if "multiSelect" not in q: + q["multiSelect"] = False + + return fixed + + +def _fix_agent(tool_input: dict) -> dict: + """ + 修正 Agent 工具参数 + + Claude Code 期望的格式: + { + "description": "...", + "prompt": "..." + } + """ + fixed = dict(tool_input) + + # 确保有 description 字段 + if "description" not in fixed: + fixed["description"] = "Execute sub-task" + + # 确保有 prompt 字段 + if "prompt" not in fixed: + fixed["prompt"] = fixed.get("description", "Execute the task") + + return fixed + + +def _fix_read(tool_input: dict) -> dict: + """ + 修正 Read 工具参数 + + Claude Code 期望的格式: + { + "file_path": "..." + } + """ + fixed = dict(tool_input) + + # 确保有 file_path 字段 + if "file_path" not in fixed: + if "path" in fixed: + fixed["file_path"] = fixed.pop("path") + elif "filename" in fixed: + fixed["file_path"] = fixed.pop("filename") + + return fixed + + +def _fix_bash(tool_input: dict) -> dict: + """ + 修正 Bash 工具参数 + + Claude Code 期望的格式: + { + "command": "...", + "description": "..." (optional) + } + """ + fixed = dict(tool_input) + + # 确保有 command 字段 + if "command" not in fixed: + if "cmd" in fixed: + fixed["command"] = fixed.pop("cmd") + elif "script" in fixed: + fixed["command"] = fixed.pop("script") + + return fixed diff --git a/backend/services/topic_isolation.py b/backend/services/topic_isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2ec5dca049e0d274f125c7fe77f8aecda64abe --- /dev/null +++ b/backend/services/topic_isolation.py @@ -0,0 +1,92 @@ +"""话题隔离检测:判断新 user 消息是否开启了与历史无关的新任务。 + +目标:Claude Code 客户端会在同一 session 里把所有历史都发过来。 +但用户意图可能完全切换(如从"读文件"转到"浏览器注册")。 +若不做切分,旧任务的工具调用历史会误导模型(表现:重新 Read 文件而非打开浏览器)。 + +判定逻辑(启发式,不用模型): + 1. 抽取每条 user 消息的"关键实体": + - 文件路径(E:/xxx, /home/xxx, C:\\xxx 等) + - URL(http://... https://...) + - 专名 / 引号字符串 / 驼峰标识符 + 2. 比较最新 user 消息实体集 vs 历史 first user 实体集的 Jaccard 相似度 + 3. 若:最新 user 有自己的非空实体集 AND 与历史 first user 实体集 Jaccard < 0.1 + → 判定为新任务 → 调用方丢弃历史 +""" + +from __future__ import annotations + +import re + +_URL_RE = re.compile(r"https?://[^\s)'\"<>]+", re.IGNORECASE) +_WIN_PATH_RE = re.compile(r"[A-Z]:[\\/](?:[^\s<>'\"|:?*]+[\\/])*[^\s<>'\"|:?*\\/]+", re.IGNORECASE) +_NIX_PATH_RE = re.compile(r"/(?:[\w.-]+/)+[\w.-]+") +_CAMEL_RE = re.compile(r"[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+") +_ID_RE = re.compile(r"\b[a-zA-Z_][a-zA-Z0-9_]{3,}(?:\.[a-zA-Z0-9_]+)?\b") + + +_STOPWORDS = { + # 中英文功能词,不作实体 + "http", "https", "the", "and", "for", "with", "from", "into", "this", "that", "then", + "have", "been", "will", "should", "would", "then", "next", "also", + "给我", "这个", "那个", "就是", "然后", "一下", "请", "帮我", "需要", "进行", "操作", + "read", "write", "read_file", "read_dir", +} + + +def _extract_entities(text: str) -> set[str]: + if not text: + return set() + entities: set[str] = set() + for m in _URL_RE.findall(text): + entities.add(m.rstrip(".,;")) + # 再拆域名主体 + dom = re.search(r"//([^/]+)", m) + if dom: + entities.add(dom.group(1).lower()) + for m in _WIN_PATH_RE.findall(text): + entities.add(m.replace("\\", "/")) + last = m.replace("\\", "/").rsplit("/", 1)[-1] + if last: + entities.add(last) + for m in _NIX_PATH_RE.findall(text): + entities.add(m) + last = m.rsplit("/", 1)[-1] + if last: + entities.add(last) + for m in _CAMEL_RE.findall(text): + if m.lower() not in _STOPWORDS: + entities.add(m) + # 含 .py .md .json 等扩展名的标识 + for m in re.findall(r"\b[\w-]+\.[a-zA-Z0-9]{1,5}\b", text): + if "." in m and m.lower() not in _STOPWORDS: + entities.add(m) + return {e for e in entities if len(e) >= 4} + + +def detect_topic_change( + first_user_text: str, + last_user_text: str, + *, + jaccard_threshold: float = 0.1, +) -> bool: + """若 last user 有自己的实体集 AND 与 first user 实体集的 Jaccard < 阈值 → 新任务。 + + 空文本或首条==最后 一条 → 非新任务(保守不切)。 + """ + if not first_user_text or not last_user_text: + return False + if first_user_text.strip() == last_user_text.strip(): + return False + last_entities = _extract_entities(last_user_text) + if not last_entities: + return False # 最新 user 没有识别实体,不敢妄判 + first_entities = _extract_entities(first_user_text) + if not first_entities: + return False + intersect = last_entities & first_entities + union = last_entities | first_entities + if not union: + return False + jaccard = len(intersect) / len(union) + return jaccard < jaccard_threshold diff --git a/backend/services/truncation_recovery.py b/backend/services/truncation_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..1edc9e3e430463f26704c08afa1dde1a6814f2bd --- /dev/null +++ b/backend/services/truncation_recovery.py @@ -0,0 +1,104 @@ +"""截断检测 + 自动续写。 + +动机: + 上游 Qwen 的 max_output_tokens 较小,长工具调用(Write 大文件、Edit 长补丁)经常 + 在 JSON 中途被截断。客户端(Claude Code)看到不完整的 ##TOOL_CALL## 块会解析失败 + 直接把它当纯文本返回给用户,导致任务失败。 + +做法: + 1. isTruncated(text):检测 ##TOOL_CALL## 开标签数 > ##END_CALL## 闭标签数 + → 说明有一个 action block 尚未闭合 → 需续写 + 2. autoContinue(req, initialResponse): + - 构造续写请求:丢弃全部工具定义和历史(省 token) + - 只保留 initialResponse 末尾 2000 字节作为 anchor + - 在 assistant 角色塞入这个 anchor + user "请从中断点继续,不要重复" + - 收到续写 → deduplicateContinuation 去掉与 existing 尾部的重叠 + - 拼接,若还是截断继续下一轮,最多 MAX_AUTO_CONTINUE 次 +""" + +from __future__ import annotations + +import re + + +_TOOL_CALL_OPEN_RE = re.compile(r"##TOOL_CALL##", re.IGNORECASE) +_TOOL_CALL_CLOSE_RE = re.compile(r"##END_CALL##", re.IGNORECASE) + + +def is_truncated(text: str) -> bool: + """检测响应是否在 ##TOOL_CALL## 块中间被截断。""" + if not text or not text.strip(): + return False + trimmed = text.rstrip() + opens = len(_TOOL_CALL_OPEN_RE.findall(trimmed)) + closes = len(_TOOL_CALL_CLOSE_RE.findall(trimmed)) + if opens > closes: + return True + # 无 action block 的纯文本截断检测 + if opens == 0: + # 以逗号、冒号、开括号、反斜杠结尾 → 明显未完成 + if re.search(r"[,;:\[{(\\]\s*$", trimmed): + return True + return False + + +def deduplicate_continuation(existing: str, continuation: str) -> str: + """在 existing 的尾部和 continuation 的头部之间寻找最长重叠, + 返回去除重叠后的 continuation 部分。""" + if not existing or not continuation: + return continuation + max_overlap = min(500, len(existing), len(continuation)) + if max_overlap < 10: + return continuation + + # 尝试字符级最长匹配 + best_overlap = 0 + for length in range(max_overlap, 9, -1): + prefix = continuation[:length] + if existing.endswith(prefix): + best_overlap = length + break + + if best_overlap >= 10: + return continuation[best_overlap:] + + # 行级匹配(对付格式微差) + tail_lines = existing.splitlines()[-20:] + cont_lines = continuation.splitlines() + if tail_lines and cont_lines: + first_cont = cont_lines[0].strip() + if first_cont: + for i in range(len(tail_lines)): + if tail_lines[i].strip() != first_cont: + continue + matched = 1 + for k in range(1, len(cont_lines)): + if i + k >= len(tail_lines): + break + if cont_lines[k].strip() == tail_lines[i + k].strip(): + matched += 1 + else: + break + if matched >= 2: + return "\n".join(cont_lines[matched:]) + + return continuation + + +def build_continuation_prompt(partial_response: str, anchor_chars: int = 2000) -> tuple[str, str]: + """构造续写请求的 (assistant_context, user_followup)。 + + - assistant_context:partial_response 的末尾 anchor_chars 字符(让上游知道之前输出过什么) + - user_followup:要求严格从中断点继续,不要重复已产出 + """ + anchor = partial_response[-anchor_chars:] if len(partial_response) > anchor_chars else partial_response + assistant_ctx = ("...\n" + anchor) if len(partial_response) > anchor_chars else anchor + followup = ( + "Your previous response was cut off mid-output. The last part was:\n\n" + "```\n" + f"...{anchor[-300:] if len(anchor) > 300 else anchor}\n" + "```\n\n" + "Continue EXACTLY from where you stopped. DO NOT repeat any content already generated. " + "DO NOT restart the response. Output ONLY the remaining content, starting immediately from the cut-off point." + ) + return assistant_ctx, followup diff --git a/backend/services/upstream_file_uploader.py b/backend/services/upstream_file_uploader.py new file mode 100644 index 0000000000000000000000000000000000000000..82a6f9c584b6f6391f675f25a80d9ed9d9ab141b --- /dev/null +++ b/backend/services/upstream_file_uploader.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import json +import mimetypes +import time +import uuid +from pathlib import Path +from typing import Any + +import oss2 + + +def _file_class_from_content_type(content_type: str) -> str: + lowered = (content_type or "").lower() + if lowered.startswith("image/"): + return "image" + if lowered.startswith("audio/"): + return "audio" + if lowered.startswith("video/"): + return "video" + return "document" + + +def _normalize_sign_region(region: str) -> str: + region = (region or "").strip() + if region.startswith("oss-"): + return region[len("oss-"):] + return region + + +class UpstreamFileUploader: + def __init__(self, client, settings): + self.client = client + self.settings = settings + + async def upload_local_file(self, acc, local_file_meta: dict[str, Any]) -> dict[str, Any]: + filename = local_file_meta["filename"] + file_path = local_file_meta["path"] + content_type = local_file_meta.get("content_type") or mimetypes.guess_type(filename)[0] or "application/octet-stream" + raw = Path(file_path).read_bytes() + + # 与 chat.qwen.ai 前端一致: + # getFileType() → image/video/audio/file;filesize 传字符串 + filetype = _file_class_from_content_type(content_type) + sts_resp = await self.client._request_json( + "POST", + "/api/v2/files/getstsToken", + acc.token, + { + "filename": filename, + "filesize": str(len(raw)), + "filetype": filetype, + }, + timeout=20.0, + ) + if sts_resp.get("status") != 200: + raise RuntimeError(f"getstsToken failed: {sts_resp.get('status')} {sts_resp.get('body', '')[:200]}") + sts_data = json.loads(sts_resp.get("body", "{}")) + sts = (sts_data.get("data") or {}) if isinstance(sts_data, dict) else {} + file_id = sts.get("file_id") + file_path_remote = sts.get("file_path", "") + bucketname = sts.get("bucketname", "") + endpoint = sts.get("endpoint", "") + region = _normalize_sign_region(sts.get("region", "")) + access_key_id = sts.get("access_key_id", "") + access_key_secret = sts.get("access_key_secret", "") + security_token = sts.get("security_token", "") + if not file_id or not file_path_remote or not bucketname or not endpoint: + raise RuntimeError(f"getstsToken missing file data: {sts_data}") + + auth = oss2.StsAuth(access_key_id, access_key_secret, security_token, auth_version='v4') + bucket = oss2.Bucket( + auth, + f"https://{endpoint}", + bucketname, + region=region, + ) + put_result = bucket.put_object( + file_path_remote, + raw, + headers={"Content-Type": content_type}, + ) + if getattr(put_result, 'status', None) not in (200, 201): + raise RuntimeError(f"OSS put_object failed: status={getattr(put_result, 'status', None)}") + + # 图片/音视频作为 vision 参考时,前端通常只拿 file_id + CDN url, + # 不强制走 document parse。parse 对部分图片会误报「上传的文档内容为空」(1040)。 + parse_status = "skipped" + if filetype not in {"image", "video", "audio"}: + parse_resp = await self.client._request_json( + "POST", + "/api/v2/files/parse", + acc.token, + {"file_id": file_id}, + timeout=20.0, + ) + if parse_resp.get("status") != 200: + raise RuntimeError(f"files/parse failed: {parse_resp.get('status')} {parse_resp.get('body', '')[:200]}") + + deadline = time.time() + self.settings.CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS + parse_status = "pending" + while time.time() < deadline: + status_resp = await self.client._request_json( + "POST", + "/api/v2/files/parse/status", + acc.token, + {"file_id_list": [file_id]}, + timeout=20.0, + ) + if status_resp.get("status") != 200: + raise RuntimeError( + f"files/parse/status failed: {status_resp.get('status')} {status_resp.get('body', '')[:200]}" + ) + status_data = json.loads(status_resp.get("body", "{}")) + rows = status_data.get("data") or [] + row = rows[0] if isinstance(rows, list) and rows else {} + parse_status = row.get("status", "pending") + if parse_status == "success": + break + if parse_status in ("failed", "error"): + raise RuntimeError(f"file parse failed: {row}") + await __import__('asyncio').sleep(1.0) + + if parse_status != "success": + raise RuntimeError(f"file parse timeout: {file_id}") + + user_id = file_path_remote.split('/', 1)[0] if '/' in file_path_remote else "" + now_ms = int(time.time() * 1000) + put_url = f"https://{bucketname}.{endpoint}/{file_path_remote.lstrip('/')}" + remote_ref = { + "type": "file", + "file": { + "created_at": now_ms, + "data": {}, + "filename": filename, + "hash": None, + "id": file_id, + "user_id": user_id, + "meta": { + "name": filename, + "size": len(raw), + "content_type": content_type, + "parse_meta": {"parse_status": parse_status}, + }, + "update_at": now_ms, + }, + "id": file_id, + "url": put_url, + "name": filename, + "collection_name": "", + "progress": 0, + "status": "uploaded", + "greenNet": "success", + "size": len(raw), + "error": "", + "itemId": str(uuid.uuid4()), + "file_type": content_type, + "showType": "file", + "file_class": _file_class_from_content_type(content_type), + "uploadTaskId": str(uuid.uuid4()), + } + return { + "remote_file_id": file_id, + "remote_object_key": file_path_remote, + "filename": filename, + "content_type": content_type, + "parse_status": parse_status, + "remote_ref": remote_ref, + } + + async def delete_remote_file(self, acc, remote_meta: dict[str, Any]) -> bool: + # Qwen web upload delete API has not been fully confirmed yet. + return False diff --git a/backend/toolcall/__init__.py b/backend/toolcall/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d94d2d4eeb09049ed2c9ef8d3e0bbcfce9fdd399 --- /dev/null +++ b/backend/toolcall/__init__.py @@ -0,0 +1,6 @@ +"""Tool call parsing helpers.""" + +from .parser import parse_tool_calls_detailed +from .stream_state import StreamingToolCallState + +__all__ = ["parse_tool_calls_detailed", "StreamingToolCallState"] diff --git a/backend/toolcall/fallback_textkv.py b/backend/toolcall/fallback_textkv.py new file mode 100644 index 0000000000000000000000000000000000000000..e28cd0f1416ff524c98c2efc74c5fac4ff6a9897 --- /dev/null +++ b/backend/toolcall/fallback_textkv.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from .normalize import normalize_arguments, normalize_tool_name + + +def parse_textkv_format(text: str, allowed_names: set[str]) -> list[dict[str, object]]: + name = None + arguments = None + + for raw_line in text.splitlines(): + line = raw_line.strip() + if not line or ":" not in line: + continue + key, value = line.split(":", 1) + key = key.strip().lower() + value = value.strip() + if key == "function.name": + name = value + elif key == "function.arguments": + arguments = value + + if not name: + return [] + + return [{ + "name": normalize_tool_name(name, allowed_names), + "input": normalize_arguments(arguments), + }] diff --git a/backend/toolcall/formats_json.py b/backend/toolcall/formats_json.py new file mode 100644 index 0000000000000000000000000000000000000000..ec67ec7e76a2b31795abd2fd05a18e692a15c268 --- /dev/null +++ b/backend/toolcall/formats_json.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import json +import re +from typing import Any + +from .normalize import normalize_arguments, normalize_tool_name + + +JSON_INPUT_KEYS = ("input", "arguments", "args", "parameters") + + +def _repair_loose_json(text: str) -> str: + repaired = text.strip() + if not repaired: + return repaired + repaired = repaired.replace('"name="', '"name": "') + repaired = re.sub(r'"name=([^",}]+)"', r'"name": "\1"', repaired) + repaired = re.sub(r'"name=([^",}]+)', r'"name": "\1"', repaired) + repaired = re.sub(r'"name\s*=\s*"', '"name": "', repaired) + repaired = re.sub(r'"(name|input|arguments|args|parameters)"\s*=\s*', r'"\1": ', repaired) + return repaired + + +def _extract_call(payload: object, allowed_names: set[str]) -> dict[str, Any] | None: + if not isinstance(payload, dict): + return None + + # Qwen / OpenAI 官方单对象格式:{"id":"...","type":"function","function":{"name":...,"arguments":"..."}} + # name 和 arguments 嵌在 function 子字段里,不是顶层。向下穿透一层再提取。 + nested_function = payload.get("function") + if isinstance(nested_function, dict) and nested_function.get("name"): + payload = nested_function + + name = payload.get("name") + if not name: + return None + + raw_input = payload.get("input") + if "input" not in payload: + for key in JSON_INPUT_KEYS[1:]: + if key in payload: + raw_input = payload[key] + break + else: + raw_input = {} + return { + "name": name if isinstance(name, str) and name in allowed_names else normalize_tool_name(name, allowed_names), + "input": normalize_arguments(raw_input), + } + + +def parse_json_format(text: str, allowed_names: set[str]) -> list[dict[str, Any]]: + stripped = text.strip() + if stripped.startswith("```"): + stripped = stripped.removeprefix("```json").removeprefix("```").strip() + if stripped.endswith("```"): + stripped = stripped[:-3].strip() + + try: + payload = json.loads(stripped) + except (json.JSONDecodeError, TypeError, ValueError): + repaired = _repair_loose_json(stripped) + if repaired == stripped: + return [] + try: + payload = json.loads(repaired) + except (json.JSONDecodeError, TypeError, ValueError): + return [] + + if isinstance(payload, dict) and isinstance(payload.get("tool_calls"), list): + calls = [] + for item in payload["tool_calls"]: + if not isinstance(item, dict): + continue + function_payload = item.get("function") + if not isinstance(function_payload, dict): + continue + call = _extract_call(function_payload, allowed_names) + if call: + calls.append(call) + return calls + + call = _extract_call(payload, allowed_names) if isinstance(payload, dict) else None + return [call] if call else [] diff --git a/backend/toolcall/formats_xml.py b/backend/toolcall/formats_xml.py new file mode 100644 index 0000000000000000000000000000000000000000..ce75b7057e97b339fcce7e728160a14500839460 --- /dev/null +++ b/backend/toolcall/formats_xml.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import json +import re +from xml.etree import ElementTree + +from .normalize import normalize_tool_name + + +def parse_xml_format(text: str, allowed_names: set[str]) -> list[dict[str, object]]: + stripped = text.strip() + + tool_call_match = re.search(r"\s*(\{[\s\S]*?\})\s*", stripped, re.IGNORECASE) + if tool_call_match: + try: + payload = json.loads(tool_call_match.group(1)) + except (json.JSONDecodeError, TypeError, ValueError): + payload = None + if isinstance(payload, dict) and payload.get("name"): + raw_input = payload.get("input", payload.get("arguments", payload.get("args", payload.get("parameters", {})))) + if isinstance(raw_input, str): + try: + raw_input = json.loads(raw_input) + except (json.JSONDecodeError, TypeError, ValueError): + raw_input = {"value": raw_input} + return [{ + "name": normalize_tool_name(str(payload.get("name", "")), allowed_names), + "input": raw_input if isinstance(raw_input, dict) else {}, + }] + + if not stripped.startswith(" str: + lowered = value.strip().lower() + if not lowered: + return "" + return re.sub(r"[^a-z0-9]+", "", lowered) + + +def build_tool_name_registry(allowed_names: Iterable[str]) -> dict[str, str]: + registry: dict[str, str] = {} + for allowed_name in allowed_names: + if not isinstance(allowed_name, str): + continue + canonical = allowed_name.strip() + if not canonical: + continue + for alias in {canonical, canonical.lower(), _tool_alias_key(canonical)}: + key = _tool_alias_key(alias) + if key and key not in registry: + registry[key] = canonical + return registry + + +def normalize_tool_name(name: str, allowed_names: Iterable[str]) -> str: + if not isinstance(name, str) or not name: + return name + + allowed_list = [candidate for candidate in allowed_names if candidate] + if not allowed_list: + return name + + for allowed_name in allowed_list: + if allowed_name == name: + return allowed_name + + registry = build_tool_name_registry(allowed_list) + return registry.get(_tool_alias_key(name), name) + + +def normalize_arguments(value: Any) -> dict[str, Any]: + if isinstance(value, str): + stripped = value.strip() + if not stripped: + return {} + try: + parsed = json.loads(stripped) + except (json.JSONDecodeError, TypeError, ValueError): + return {"value": value} + return parsed if isinstance(parsed, dict) else {"value": parsed} + + if value is None: + return {} + + if isinstance(value, dict): + return value + + return {"value": value} diff --git a/backend/toolcall/parser.py b/backend/toolcall/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f37b7908fb2dc433f5c6c4fb40abda1a9967f9f7 --- /dev/null +++ b/backend/toolcall/parser.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import json + +from backend.toolcall.fallback_textkv import parse_textkv_format +from backend.toolcall.formats_json import parse_json_format +from backend.toolcall.formats_xml import parse_xml_format + + +def _has_top_level_json_tool_syntax(text: str) -> bool: + stripped = text.strip() + if stripped.startswith("```"): + stripped = stripped.removeprefix("```json").removeprefix("```").strip() + if stripped.endswith("```"): + stripped = stripped[:-3].strip() + + if not stripped.startswith("{"): + return False + + repaired = stripped.replace('"name="', '"name": "') + if '"name=' in repaired: + return True + + try: + payload = json.loads(repaired) + except (json.JSONDecodeError, TypeError, ValueError): + return False + + if not isinstance(payload, dict): + return False + + if isinstance(payload.get("tool_calls"), list): + return True + + has_name = isinstance(payload.get("name"), str) and bool(payload.get("name")) + has_args = any(key in payload for key in ("input", "arguments", "args", "parameters")) + return has_name and has_args + + +def _has_xml_like_tool_syntax(text: str) -> bool: + lowered = text.lower() + return any(marker in lowered for marker in ("")) + + +def parse_tool_calls_detailed(text: str, allowed_names: set[str]) -> dict[str, object]: + candidates = [ + ("json", parse_json_format(text, allowed_names)), + ("xml", parse_xml_format(text, allowed_names)), + ("textkv", parse_textkv_format(text, allowed_names)), + ] + + for source, calls in candidates: + if calls: + return { + "calls": calls, + "source": source, + "saw_tool_syntax": True, + } + + return { + "calls": [], + "source": None, + "saw_tool_syntax": ( + _has_top_level_json_tool_syntax(text) + or _has_xml_like_tool_syntax(text) + or any(marker in text for marker in ("function.name:", "function.arguments:", '"name="')) + ), + } diff --git a/backend/toolcall/stream_state.py b/backend/toolcall/stream_state.py new file mode 100644 index 0000000000000000000000000000000000000000..02d8c322a958da31e9585699605210943aecc772 --- /dev/null +++ b/backend/toolcall/stream_state.py @@ -0,0 +1,72 @@ +import json +from dataclasses import dataclass +from typing import Any + + +@dataclass +class _ToolCallBuffer: + name: str = "" + args: str = "" + emitted: bool = False + + +class StreamingToolCallState: + def __init__(self) -> None: + self._calls: dict[str, _ToolCallBuffer] = {} + self._anonymous_call_seq = 0 + + def process_event(self, event: dict[str, Any]) -> list[dict[str, Any]]: + if event.get("type") != "delta" or event.get("phase") != "tool_call": + return [] + + tool_call_id = self._resolve_tool_call_id(event) + buffer = self._calls.setdefault(tool_call_id, _ToolCallBuffer()) + content = event.get("content", "") + + self._apply_chunk(buffer, content) + + if buffer.emitted or not buffer.name or not self.is_complete_json_object(buffer.args): + return [] + + parsed_input = json.loads(buffer.args) if buffer.args else {} + buffer.emitted = True + return [{"type": "tool_use", "id": tool_call_id, "name": buffer.name, "input": parsed_input}] + + @staticmethod + def is_complete_json_object(text: str) -> bool: + if not text: + return False + try: + parsed = json.loads(text) + except (json.JSONDecodeError, TypeError, ValueError): + return False + return isinstance(parsed, dict) + + def _resolve_tool_call_id(self, event: dict[str, Any]) -> str: + extra = event.get("extra") or {} + tool_call_id = extra.get("tool_call_id") + if tool_call_id: + return tool_call_id + + index = extra.get("index") + if index is not None: + return f"tc_idx_{index}" + + self._anonymous_call_seq += 1 + return f"tc_anonymous_{self._anonymous_call_seq}" + + @staticmethod + def _apply_chunk(buffer: _ToolCallBuffer, content: str) -> None: + try: + chunk = json.loads(content) + except (json.JSONDecodeError, TypeError, ValueError): + buffer.args += content + return + + if isinstance(chunk, dict): + name = chunk.get("name") + if name and not buffer.name: + buffer.name = name + arguments = chunk.get("arguments") + if isinstance(arguments, str): + buffer.args += arguments diff --git a/backend/upstream/__init__.py b/backend/upstream/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e760d1f4a894a67ab7a090d7459c7dc139dadff5 --- /dev/null +++ b/backend/upstream/__init__.py @@ -0,0 +1 @@ +# Upstream package diff --git a/backend/upstream/payload_builder.py b/backend/upstream/payload_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..481f2078266f102a5af5b62c07e82131c01b8a0d --- /dev/null +++ b/backend/upstream/payload_builder.py @@ -0,0 +1,150 @@ +import time +import uuid + + +CUSTOM_TOOL_COMPAT_FEATURE_CONFIG = { + "thinking_enabled": False, + "output_schema": "phase", + "research_mode": "normal", + "auto_thinking": False, + "thinking_mode": "Auto", + "thinking_format": "summary", + "auto_search": False, + "code_interpreter": False, + "plugins_enabled": False, +} + +CUSTOM_TOOL_LOW_LATENCY_OVERRIDES = { + "thinking_enabled": False, + "auto_thinking": False, +} + + +def _extract_img_url_from_files(files: list[dict] | None) -> str | None: + """Best-effort extract a public/OSS image URL from uploaded file refs for i2v.""" + if not files: + return None + for f in files: + if not isinstance(f, dict): + continue + for key in ("url", "img_url", "image_url", "src"): + val = f.get(key) + if isinstance(val, str) and val.startswith("http"): + return val + file_obj = f.get("file") + if isinstance(file_obj, dict): + for key in ("url", "img_url", "image_url"): + val = file_obj.get(key) + if isinstance(val, str) and val.startswith("http"): + return val + meta = file_obj.get("meta") if isinstance(file_obj.get("meta"), dict) else {} + for key in ("url", "img_url", "image_url"): + val = meta.get(key) + if isinstance(val, str) and val.startswith("http"): + return val + return None + + +def build_chat_payload( + chat_id: str, + model: str, + content: str, + has_custom_tools: bool = False, + files: list[dict] | None = None, + chat_type: str = "t2t", + size: str | None = None, + img_url: str | None = None, +) -> dict: + ts = int(time.time()) + # Qwen3.8 preview currently rejects requests with thinking_enabled=false + # ("invalid_input"). Force thinking for 3.8* models only. + is_qwen38 = isinstance(model, str) and ( + "qwen3.8" in model.lower() or model.lower().startswith("qwen-3.8") + ) + if chat_type == "t2t": + feature_config = { + **CUSTOM_TOOL_COMPAT_FEATURE_CONFIG, + **(CUSTOM_TOOL_LOW_LATENCY_OVERRIDES if has_custom_tools else {}), + # Our Anthropic/OpenAI bridge relies on textual JSON/XML tool directives + # that are parsed locally. Enabling Qwen native function_calling here causes + # upstream interception such as `Tool Read/Bash does not exists.` for custom + # local tools that only exist in the bridge layer. + "function_calling": False, + # Additional safeguards to prevent tool call interception + "enable_tools": False, + "enable_function_call": False, + "tool_choice": "none", + } + if is_qwen38: + feature_config["thinking_enabled"] = True + feature_config["auto_thinking"] = False + feature_config["thinking_mode"] = "Auto" + else: + # Qwen feature modes such as text-to-video use upstream-native async tasks. + # Do not disable native tools here, or the task handoff can be suppressed. + feature_config = { + "thinking_enabled": False, + "output_schema": "phase", + "research_mode": "normal", + } + + # Frontend behavior: +# - UI feature is VideoGeneration (t2v) +# - if files contain type=="image", it auto-switches chat_type/sub_chat_type to i2v +# - file object shape: type=image, file_class=vision, showType=image, url=... + resolved_img_url = img_url or _extract_img_url_from_files(files) + effective_chat_type = chat_type + has_image_files = bool( + files and any(isinstance(f, dict) and f.get("type") == "image" and f.get("url") for f in files) + ) + # 仅视频场景(t2v/i2v)在有参考图时自动切 i2v。 + # 图生图(t2i + 参考图)必须保持 t2i,否则会被当成视频任务并空响应。 + if has_image_files and chat_type in {"t2v", "i2v"}: + effective_chat_type = "i2v" + + meta = {"subChatType": effective_chat_type} + # Qwen t2v/t2i size 偏好 1280*720 这种星号格式 + norm_size = size + if isinstance(size, str) and "x" in size.lower() and "*" not in size: + norm_size = size.lower().replace("x", "*") + if norm_size: + meta["size"] = norm_size + # Some task workers read input.img_url from extra.meta + if effective_chat_type == "i2v" and resolved_img_url: + meta["img_url"] = resolved_img_url + meta["input"] = {"img_url": resolved_img_url} + if effective_chat_type == "t2i" and resolved_img_url: + meta["img_url"] = resolved_img_url + meta["input"] = {"img_url": resolved_img_url} + + message = { + "fid": str(uuid.uuid4()), + "parentId": None, + "childrenIds": [str(uuid.uuid4())], + "role": "user", + "content": content, + "user_action": "chat", + "files": files or [], + "timestamp": ts, + "models": [model], + "chat_type": effective_chat_type, + "feature_config": feature_config, + "extra": {"meta": meta}, + "sub_chat_type": effective_chat_type, + "parent_id": None, + } + + payload = { + "stream": True, + "version": "2.1", + "incremental_output": True, + "chat_id": chat_id, + "chat_mode": "normal", + "model": model, + "parent_id": None, + "messages": [message], + "timestamp": ts, + } + if norm_size: + payload["size"] = norm_size + return payload diff --git a/backend/upstream/qwen_executor.py b/backend/upstream/qwen_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..f5071142185b5f5deeed88f3024f8183585c31ac --- /dev/null +++ b/backend/upstream/qwen_executor.py @@ -0,0 +1,270 @@ +import asyncio +import json +import logging +import time + +from backend.core.config import settings +from backend.core.request_logging import update_request_context +from backend.services.auth_resolver import AuthResolver +from backend.upstream.payload_builder import build_chat_payload +from backend.upstream.sse_consumer import parse_sse_chunk + +log = logging.getLogger("qwen2api.executor") + + +class QwenExecutor: + def __init__(self, engine, account_pool): + self.engine = engine + self.account_pool = account_pool + self.auth_resolver = AuthResolver(account_pool) if account_pool is not None else None + # 会在 app 启动时被 main.py 注入;若未注入则为 None,走同步 create_chat + self.chat_id_pool = None + + async def create_chat(self, token: str, model: str, chat_type: str = "t2t") -> str: + # 预热池只用于普通文本会话;t2v/t2i 等必须新建对应 chat_type + if chat_type == "t2t" and self.chat_id_pool is not None and self.account_pool is not None: + try: + acc = next((a for a in self.account_pool.accounts if a.token == token), None) + if acc is not None: + cached = await self.chat_id_pool.acquire(acc.email, model) + if cached: + log.info(f"[上游] 预热池命中 邮箱={acc.email} 会话={cached}") + return cached + except Exception as e: + log.debug(f"[Executor] chat_id_pool lookup failed: {e}") + + request_fn = getattr(self.engine, "_request_json", None) or getattr(self.engine, "api_call", None) + if request_fn is None: + raise Exception("request transport unavailable") + + ts = int(time.time()) + body = { + "title": f"api_{ts}", + "models": [model], + "chat_mode": "normal", + "chat_type": chat_type, + "timestamp": ts, + } + + if getattr(self.engine, "_request_json", None) is not None: + r = await request_fn("POST", "/api/v2/chats/new", token, body, timeout=30.0) + else: + r = await request_fn("POST", "/api/v2/chats/new", token, body) + body_text = r.get("body", "") + if r["status"] != 200: + body_lower = body_text.lower() + if ( + r["status"] in (401, 403) + or "unauthorized" in body_lower + or "forbidden" in body_lower + or "token" in body_lower + or "login" in body_lower + or "401" in body_text + or "403" in body_text + ): + raise Exception(f"unauthorized: create_chat HTTP {r['status']}: {body_text[:100]}") + if r["status"] == 429: + raise Exception("429 Too Many Requests") + raise Exception(f"create_chat HTTP {r['status']}: {body_text[:100]}") + + # 检测 WAF 拦截(非账号问题) + if "aliyun_waf" in body_text.lower() or "captcha" in body_text.lower() or " 5.0: + log.warning(f"[上游] 异常短回复 仅 {total_output_chars} 字符 耗时 {elapsed:.1f}s — 疑似上游超时") + raise Exception(f"Upstream timeout suspected: only {total_output_chars} chars in {elapsed:.1f}s") + + log.info(f"[上游] 流结束 会话={chat_id} 总耗时={elapsed:.3f}s 流字节={total_output_chars}") + + async def chat_stream_events_with_retry( + self, + model: str, + content: str, + has_custom_tools: bool = False, + files: list[dict] | None = None, + fixed_account=None, + existing_chat_id: str | None = None, + ): + exclude = set() + if fixed_account is not None: + update_request_context(upstream_attempt=1) + acc = fixed_account + try: + log.info(f"[上游] 使用指定账号 账号={acc.email} 模型={model}") + chat_id = existing_chat_id or await self.create_chat(acc.token, model) + update_request_context(chat_id=chat_id) + if existing_chat_id: + log.info(f"[上游] 复用会话 会话={chat_id} 账号={acc.email}") + else: + log.info(f"[上游] 创建会话 会话={chat_id} 账号={acc.email}") + yield {"type": "meta", "chat_id": chat_id, "acc": acc} + async for evt in self.stream(acc.token, chat_id, model, content, has_custom_tools, files=files): + yield {"type": "event", "event": evt} + return + except Exception: + self.account_pool.release(acc) + raise + + for attempt in range(settings.MAX_RETRIES): + update_request_context(upstream_attempt=attempt + 1) + acquire_start = time.perf_counter() + acc = await self.account_pool.acquire_wait(timeout=60, exclude=exclude) + acquire_elapsed = time.perf_counter() - acquire_start + if not acc: + raise Exception("No available accounts in pool (all busy or rate limited)") + + try: + log.info(f"[上游] 账号已获取 账号={acc.email} 模型={model} 第{attempt + 1}次 获取耗时={acquire_elapsed:.3f}s") + create_start = time.perf_counter() + chat_id = await self.create_chat(acc.token, model) + create_elapsed = time.perf_counter() - create_start + update_request_context(chat_id=chat_id) + log.info(f"[上游] 创建会话 会话={chat_id} 账号={acc.email} 耗时={create_elapsed:.3f}s") + yield {"type": "meta", "chat_id": chat_id, "acc": acc} + + async for evt in self.stream(acc.token, chat_id, model, content, has_custom_tools, files=files): + yield {"type": "event", "event": evt} + return + + except Exception as e: + err_msg = str(e).lower() + is_timeout = ( + "timeout" in err_msg + or "timed out" in err_msg + or "readtimeout" in err_msg + or type(e).__name__ in ("ReadTimeout", "TimeoutError", "TimeoutException") + ) + is_waf = "waf_blocked" in err_msg or "waf challenge" in err_msg or "aliyun_waf" in err_msg + + if is_waf: + # WAF 拦截不是账号问题,是服务端风控,所有账号都会面临同样的 WAF + # 因此不重试,直接抛出,让调用方得到清晰错误 + log.warning(f"[上游] WAF 拦截 账号={acc.email} 错误={e}") + self.account_pool.release(acc) + raise Exception(f"WAF blocked: Qwen WAF 拦截了本次请求。请设置 BROWSER_HEADED=1 环境变量后重启,在打开的浏览器窗口中手动完成验证码。详情: {e}") + elif is_timeout: + log.warning(f"[上游] 超时 第{attempt + 1}/{settings.MAX_RETRIES}次 账号={acc.email} 错误={e}") + exclude.add(acc.email) + elif "429" in err_msg or "rate limit" in err_msg or "too many" in err_msg: + self.account_pool.mark_rate_limited(acc) + exclude.add(acc.email) + elif "unauthorized" in err_msg or "401" in err_msg or "403" in err_msg: + self.account_pool.mark_invalid(acc) + exclude.add(acc.email) + if "activation" in err_msg or "pending" in err_msg: + acc.activation_pending = True + if self.auth_resolver is not None: + asyncio.create_task(self.auth_resolver.auto_heal_account(acc)) + else: + exclude.add(acc.email) + + self.account_pool.release(acc) + log.warning( + f"[上游] 重试 第{attempt + 1}/{settings.MAX_RETRIES}次 账号={acc.email} 错误={e}" + ) + + raise Exception(f"All {settings.MAX_RETRIES} attempts failed. Please check upstream accounts.") diff --git a/backend/upstream/sse_consumer.py b/backend/upstream/sse_consumer.py new file mode 100644 index 0000000000000000000000000000000000000000..3c1309414f5d4d243270c451fbf6ad710085c850 --- /dev/null +++ b/backend/upstream/sse_consumer.py @@ -0,0 +1,67 @@ +import json +import logging + +log = logging.getLogger("qwen2api.sse") + + +def parse_sse_chunk(chunk: str) -> list[dict]: + events = [] + for line in chunk.splitlines(): + line = line.strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if not data or data == "[DONE]": + continue + try: + obj = json.loads(data) + events.append(obj) + except Exception: + continue + + parsed = [] + for evt in events: + log.info("[SSE-DEBUG] 上游事件: keys=%s preview=%s", list(evt.keys()), str(evt)[:300]) + if evt.get("choices"): + choices = evt["choices"] + if choices: + delta = choices[0].get("delta", {}) + content = delta.get("content", "") + log.info("[SSE-DEBUG] choices事件: content=%r phase=%s finish=%s", + content, delta.get("phase"), choices[0].get("finish_reason")) + else: + content = "" + delta = {} + + # Log if content contains "Tool" and "does not exist" + if content and "Tool" in content and "does not exist" in content: + log.warning(f"[SSE] Detected tool interception: content={content!r} phase={delta.get('phase')} status={delta.get('status')} extra={delta.get('extra')}") + + parsed.append( + { + "type": "delta", + "phase": delta.get("phase", "answer"), + "content": content, + "status": delta.get("status", ""), + "extra": delta.get("extra", {}), + } + ) + else: + # 非标准格式 - 可能是 Qwen 原生格式 + log.info("[SSE-DEBUG] 非标准格式事件: %s", str(evt)[:300]) + content = evt.get("content", "") or evt.get("text", "") or evt.get("delta", "") + if isinstance(content, dict): + content = content.get("content", "") or content.get("text", "") or "" + phase = evt.get("phase", evt.get("type", "answer")) + if content: + log.info("[SSE-DEBUG] 从非标准格式提取内容: content=%r phase=%s", content, phase) + parsed.append( + { + "type": "delta", + "phase": phase, + "content": content, + "status": evt.get("status", ""), + "extra": evt.get("extra", {}), + } + ) + return parsed diff --git a/docker-compose.build.yml b/docker-compose.build.yml new file mode 100644 index 0000000000000000000000000000000000000000..b463306811f361acf83e740a71491270c93ede87 --- /dev/null +++ b/docker-compose.build.yml @@ -0,0 +1,6 @@ +services: + qwen2api: + image: ${QWEN2API_IMAGE:-qwen2api:local-fix} + build: + context: . + dockerfile: Dockerfile diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..85e735d3c222bb57a4070bdfef293d025d82e157 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,29 @@ +services: + qwen2api: + image: ${QWEN2API_IMAGE:-yujunzhixue/qwen2api:latest} + container_name: qwen2api + restart: unless-stopped + env_file: + - path: .env + required: false + ports: + - "7860:7860" + volumes: + - ./data:/workspace/data + - ./logs:/workspace/logs + shm_size: "256m" + environment: + PYTHONIOENCODING: utf-8 + PORT: "7860" + WORKERS: "1" + LOG_LEVEL: "INFO" + MAX_INFLIGHT: "2" + ACCOUNT_MIN_INTERVAL_MS: "0" + REQUEST_JITTER_MIN_MS: "0" + REQUEST_JITTER_MAX_MS: "0" + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://localhost:7860/healthz || exit 1"] + interval: 30s + timeout: 10s + start_period: 120s + retries: 3 diff --git a/frontend/.env.example b/frontend/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..ff426e61293b6e11f28fdb4e4fdf32ed3bfd7c56 --- /dev/null +++ b/frontend/.env.example @@ -0,0 +1,5 @@ +# 当前端独立部署(Vercel / 非单机模式)时,需指定后端地址 +# VITE_API_BASE_URL=https://your-backend.example.com + +# 本地开发和 Docker 单机部署时留空,由 Vite proxy / nginx 代理 +# VITE_API_BASE_URL= diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6b9171678fde48a5cf27664f7bd4e932d6dd8a0 --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,12 @@ +FROM node:20-alpine AS builder +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +RUN npm run build + +FROM nginx:alpine +COPY --from=builder /app/dist /usr/share/nginx/html +COPY nginx.conf /etc/nginx/conf.d/default.conf +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..d41a94898978b552cc09e2ed0cac1449a31fe30b --- /dev/null +++ b/frontend/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4f0a458de86fc1b5b4278cb56f3f603e133d83ab --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + frontend + + +
+ + + diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000000000000000000000000000000000000..9a83bfe6dfc9e5779843d3d2b72ba035007fdeca --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,52 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # Proxy API routes to backend + location /api/ { + proxy_pass http://backend:7860; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_read_timeout 300s; + proxy_buffering off; + } + + location /v1/ { + proxy_pass http://backend:7860; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_read_timeout 300s; + proxy_buffering off; + } + + location /anthropic/ { + proxy_pass http://backend:7860; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_read_timeout 300s; + proxy_buffering off; + } + + location /v1beta/ { + proxy_pass http://backend:7860; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_read_timeout 300s; + proxy_buffering off; + } + + location /healthz { + proxy_pass http://backend:7860; + } + + # SPA fallback: serve index.html for all non-file routes + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..ab61bffcaaf1d0cb69fb499e23fdd4ef312d6437 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,4064 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.0.0", + "dependencies": { + "@radix-ui/react-slot": "^1.2.4", + "@tailwindcss/vite": "^4.2.2", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^1.7.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "react-router-dom": "^7.14.0", + "sonner": "^2.0.7", + "tailwind-merge": "^3.5.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.4", + "@types/node": "^24.12.2", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^4.3.4", + "autoprefixer": "^10.4.27", + "eslint": "^9.39.4", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.4.0", + "postcss": "^8.5.8", + "tailwindcss": "^4.2.2", + "typescript": "~5.9.3", + "typescript-eslint": "^8.57.0", + "vite": "^6.2.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz", + "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz", + "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz", + "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz", + "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz", + "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.2.tgz", + "integrity": "sha512-sNXv5oLJ7ob93xkZ1XnxisYhGYXfaG9f65/ZgYuAu3qt7b3NadcOEhLvx28hv31PgX8SZJRYrAIPQilQmFpLVw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz", + "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz", + "integrity": "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.2" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz", + "integrity": "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz", + "integrity": "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz", + "integrity": "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz", + "integrity": "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz", + "integrity": "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz", + "integrity": "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz", + "integrity": "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz", + "integrity": "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz", + "integrity": "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz", + "integrity": "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz", + "integrity": "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz", + "integrity": "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz", + "integrity": "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz", + "integrity": "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz", + "integrity": "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz", + "integrity": "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz", + "integrity": "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz", + "integrity": "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz", + "integrity": "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz", + "integrity": "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz", + "integrity": "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz", + "integrity": "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz", + "integrity": "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz", + "integrity": "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz", + "integrity": "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tailwindcss/node": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.2.tgz", + "integrity": "sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.19.0", + "jiti": "^2.6.1", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.2.2" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.2.2.tgz", + "integrity": "sha512-qEUA07+E5kehxYp9BVMpq9E8vnJuBHfJEC0vPC5e7iL/hw7HR61aDKoVoKzrG+QKp56vhNZe4qwkRmMC0zDLvg==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.2.2", + "@tailwindcss/oxide-darwin-arm64": "4.2.2", + "@tailwindcss/oxide-darwin-x64": "4.2.2", + "@tailwindcss/oxide-freebsd-x64": "4.2.2", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.2", + "@tailwindcss/oxide-linux-arm64-gnu": "4.2.2", + "@tailwindcss/oxide-linux-arm64-musl": "4.2.2", + "@tailwindcss/oxide-linux-x64-gnu": "4.2.2", + "@tailwindcss/oxide-linux-x64-musl": "4.2.2", + "@tailwindcss/oxide-wasm32-wasi": "4.2.2", + "@tailwindcss/oxide-win32-arm64-msvc": "4.2.2", + "@tailwindcss/oxide-win32-x64-msvc": "4.2.2" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.2.2.tgz", + "integrity": "sha512-dXGR1n+P3B6748jZO/SvHZq7qBOqqzQ+yFrXpoOWWALWndF9MoSKAT3Q0fYgAzYzGhxNYOoysRvYlpixRBBoDg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.2.2.tgz", + "integrity": "sha512-iq9Qjr6knfMpZHj55/37ouZeykwbDqF21gPFtfnhCCKGDcPI/21FKC9XdMO/XyBM7qKORx6UIhGgg6jLl7BZlg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.2.2.tgz", + "integrity": "sha512-BlR+2c3nzc8f2G639LpL89YY4bdcIdUmiOOkv2GQv4/4M0vJlpXEa0JXNHhCHU7VWOKWT/CjqHdTP8aUuDJkuw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.2.2.tgz", + "integrity": "sha512-YUqUgrGMSu2CDO82hzlQ5qSb5xmx3RUrke/QgnoEx7KvmRJHQuZHZmZTLSuuHwFf0DJPybFMXMYf+WJdxHy/nQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.2.2.tgz", + "integrity": "sha512-FPdhvsW6g06T9BWT0qTwiVZYE2WIFo2dY5aCSpjG/S/u1tby+wXoslXS0kl3/KXnULlLr1E3NPRRw0g7t2kgaQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.2.2.tgz", + "integrity": "sha512-4og1V+ftEPXGttOO7eCmW7VICmzzJWgMx+QXAJRAhjrSjumCwWqMfkDrNu1LXEQzNAwz28NCUpucgQPrR4S2yw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.2.2.tgz", + "integrity": "sha512-oCfG/mS+/+XRlwNjnsNLVwnMWYH7tn/kYPsNPh+JSOMlnt93mYNCKHYzylRhI51X+TbR+ufNhhKKzm6QkqX8ag==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.2.2.tgz", + "integrity": "sha512-rTAGAkDgqbXHNp/xW0iugLVmX62wOp2PoE39BTCGKjv3Iocf6AFbRP/wZT/kuCxC9QBh9Pu8XPkv/zCZB2mcMg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.2.2.tgz", + "integrity": "sha512-XW3t3qwbIwiSyRCggeO2zxe3KWaEbM0/kW9e8+0XpBgyKU4ATYzcVSMKteZJ1iukJ3HgHBjbg9P5YPRCVUxlnQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.2.2.tgz", + "integrity": "sha512-eKSztKsmEsn1O5lJ4ZAfyn41NfG7vzCg496YiGtMDV86jz1q/irhms5O0VrY6ZwTUkFy/EKG3RfWgxSI3VbZ8Q==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.8.1", + "@emnapi/runtime": "^1.8.1", + "@emnapi/wasi-threads": "^1.1.0", + "@napi-rs/wasm-runtime": "^1.1.1", + "@tybys/wasm-util": "^0.10.1", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz", + "integrity": "sha512-qPmaQM4iKu5mxpsrWZMOZRgZv1tOZpUm+zdhhQP0VhJfyGGO3aUKdbh3gDZc/dPLQwW4eSqWGrrcWNBZWUWaXQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.2.2.tgz", + "integrity": "sha512-1T/37VvI7WyH66b+vqHj/cLwnCxt7Qt3WFu5Q8hk65aOvlwAhs7rAp1VkulBJw/N4tMirXjVnylTR72uI0HGcA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.2.2.tgz", + "integrity": "sha512-mEiF5HO1QqCLXoNEfXVA1Tzo+cYsrqV7w9Juj2wdUFyW07JRenqMG225MvPwr3ZD9N1bFQj46X7r33iHxLUW0w==", + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.2.2", + "@tailwindcss/oxide": "4.2.2", + "tailwindcss": "4.2.2" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.12.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz", + "integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.14", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", + "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.58.0.tgz", + "integrity": "sha512-RLkVSiNuUP1C2ROIWfqX+YcUfLaSnxGE/8M+Y57lopVwg9VTYYfhuz15Yf1IzCKgZj6/rIbYTmJCUSqr76r0Wg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.58.0", + "@typescript-eslint/type-utils": "8.58.0", + "@typescript-eslint/utils": "8.58.0", + "@typescript-eslint/visitor-keys": "8.58.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.58.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.58.0.tgz", + "integrity": "sha512-rLoGZIf9afaRBYsPUMtvkDWykwXwUPL60HebR4JgTI8mxfFe2cQTu3AGitANp4b9B2QlVru6WzjgB2IzJKiCSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.58.0", + "@typescript-eslint/types": "8.58.0", + "@typescript-eslint/typescript-estree": "8.58.0", + "@typescript-eslint/visitor-keys": "8.58.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.58.0.tgz", + "integrity": "sha512-8Q/wBPWLQP1j16NxoPNIKpDZFMaxl7yWIoqXWYeWO+Bbd2mjgvoF0dxP2jKZg5+x49rgKdf7Ck473M8PC3V9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.58.0", + "@typescript-eslint/types": "^8.58.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.58.0.tgz", + "integrity": "sha512-W1Lur1oF50FxSnNdGp3Vs6P+yBRSmZiw4IIjEeYxd8UQJwhUF0gDgDD/W/Tgmh73mxgEU3qX0Bzdl/NGuSPEpQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.0", + "@typescript-eslint/visitor-keys": "8.58.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.58.0.tgz", + "integrity": "sha512-doNSZEVJsWEu4htiVC+PR6NpM+pa+a4ClH9INRWOWCUzMst/VA9c4gXq92F8GUD1rwhNvRLkgjfYtFXegXQF7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.58.0.tgz", + "integrity": "sha512-aGsCQImkDIqMyx1u4PrVlbi/krmDsQUs4zAcCV6M7yPcPev+RqVlndsJy9kJ8TLihW9TZ0kbDAzctpLn5o+lOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.0", + "@typescript-eslint/typescript-estree": "8.58.0", + "@typescript-eslint/utils": "8.58.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.58.0.tgz", + "integrity": "sha512-O9CjxypDT89fbHxRfETNoAnHj/i6IpRK0CvbVN3qibxlLdo5p5hcLmUuCCrHMpxiWSwKyI8mCP7qRNYuOJ0Uww==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.58.0.tgz", + "integrity": "sha512-7vv5UWbHqew/dvs+D3e1RvLv1v2eeZ9txRHPnEEBUgSNLx5ghdzjHa0sgLWYVKssH+lYmV0JaWdoubo0ncGYLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.58.0", + "@typescript-eslint/tsconfig-utils": "8.58.0", + "@typescript-eslint/types": "8.58.0", + "@typescript-eslint/visitor-keys": "8.58.0", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.58.0.tgz", + "integrity": "sha512-RfeSqcFeHMHlAWzt4TBjWOAtoW9lnsAGiP3GbaX9uVgTYYrMbVnGONEfUCiSss+xMHFl+eHZiipmA8WkQ7FuNA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.58.0", + "@typescript-eslint/types": "8.58.0", + "@typescript-eslint/typescript-estree": "8.58.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.58.0.tgz", + "integrity": "sha512-XJ9UD9+bbDo4a4epraTwG3TsNPeiB9aShrUneAVXy8q4LuwowN+qu89/6ByLMINqvIMeI9H9hOHQtg/ijrYXzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/autoprefixer": { + "version": "10.4.27", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.27.tgz", + "integrity": "sha512-NP9APE+tO+LuJGn7/9+cohklunJsXWiaWEfV3si4Gi/XHDwVNgkwr1J3RQYFIvPy76GmJ9/bW8vyoU1LcxwKHA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.1", + "caniuse-lite": "^1.0.30001774", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.15", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.15.tgz", + "integrity": "sha512-1nfKCq9wuAZFTkA2ey/3OXXx7GzFjLdkTiFVNwlJ9WqdI706CZRIhEqjuwanjMIja+84jDLa9rcyZDPDiVkASQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browserslist": { + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001785", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001785.tgz", + "integrity": "sha512-blhOL/WNR+Km1RI/LCVAvA73xplXA7ZbjzI4YkMK9pa6T/P3F2GxjNpEkyw5repTw9IvkyrjyHpwjnhZ5FOvYQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.331", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.331.tgz", + "integrity": "sha512-IbxXrsTlD3hRodkLnbxAPP4OuJYdWCeM3IOdT+CpcMoIwIoDfCmRpEtSPfwBXxVkg9xmBeY7Lz2Eo2TDn/HC3Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.20.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz", + "integrity": "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz", + "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "9.39.4", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz", + "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.2.tgz", + "integrity": "sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": "^9 || ^10" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "dev": true, + "license": "ISC" + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.4.0.tgz", + "integrity": "sha512-hjrNztw/VajQwOLsMNT1cbJiH2muO3OROCHnbehc8eY5JyD2gqz4AcMHPqgaOR59DjgUjYAYLeH699g/eWi2jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.7.0.tgz", + "integrity": "sha512-yI7BeItCLZJTXikmK4KNUGCKoGzSvbKlfCvw44bU4fXAL6v3gYS4uHD1jzsLkfwODYwI6Drw5Tu9Z5ulDe0TSg==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.37", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz", + "integrity": "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==", + "dev": true, + "license": "MIT" + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.2.4", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", + "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.4", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", + "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.4" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-router": { + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.14.0.tgz", + "integrity": "sha512-m/xR9N4LQLmAS0ZhkY2nkPA1N7gQ5TUVa5n8TgANuDTARbn1gt+zLPXEm7W0XDTbrQ2AJSJKhoa6yx1D8BcpxQ==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.14.0.tgz", + "integrity": "sha512-2G3ajSVSZMEtmTjIklRWlNvo8wICEpLihfD/0YMDxbWK2UyP5EGfnoIn9AIQGnF3G/FX0MRbHXdFcD+rL1ZreQ==", + "license": "MIT", + "dependencies": { + "react-router": "7.14.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/rollup": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz", + "integrity": "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w==", + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.60.1", + "@rollup/rollup-android-arm64": "4.60.1", + "@rollup/rollup-darwin-arm64": "4.60.1", + "@rollup/rollup-darwin-x64": "4.60.1", + "@rollup/rollup-freebsd-arm64": "4.60.1", + "@rollup/rollup-freebsd-x64": "4.60.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", + "@rollup/rollup-linux-arm-musleabihf": "4.60.1", + "@rollup/rollup-linux-arm64-gnu": "4.60.1", + "@rollup/rollup-linux-arm64-musl": "4.60.1", + "@rollup/rollup-linux-loong64-gnu": "4.60.1", + "@rollup/rollup-linux-loong64-musl": "4.60.1", + "@rollup/rollup-linux-ppc64-gnu": "4.60.1", + "@rollup/rollup-linux-ppc64-musl": "4.60.1", + "@rollup/rollup-linux-riscv64-gnu": "4.60.1", + "@rollup/rollup-linux-riscv64-musl": "4.60.1", + "@rollup/rollup-linux-s390x-gnu": "4.60.1", + "@rollup/rollup-linux-x64-gnu": "4.60.1", + "@rollup/rollup-linux-x64-musl": "4.60.1", + "@rollup/rollup-openbsd-x64": "4.60.1", + "@rollup/rollup-openharmony-arm64": "4.60.1", + "@rollup/rollup-win32-arm64-msvc": "4.60.1", + "@rollup/rollup-win32-ia32-msvc": "4.60.1", + "@rollup/rollup-win32-x64-gnu": "4.60.1", + "@rollup/rollup-win32-x64-msvc": "4.60.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/sonner": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz", + "integrity": "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==", + "license": "MIT", + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tailwind-merge": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.5.0.tgz", + "integrity": "sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.2.tgz", + "integrity": "sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==", + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.2.tgz", + "integrity": "sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD", + "optional": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.58.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.58.0.tgz", + "integrity": "sha512-e2TQzKfaI85fO+F3QywtX+tCTsu/D3WW5LVU6nz8hTFKFZ8yBJ6mSYRpXqdR3mFjPWmO0eWsTa5f+UpAOe/FMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.58.0", + "@typescript-eslint/parser": "8.58.0", + "@typescript-eslint/typescript-estree": "8.58.0", + "@typescript-eslint/utils": "8.58.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz", + "integrity": "sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==", + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..70f07488ed7f5c6ec24abaa7c54eaee3f9a5c031 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,41 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite --host", + "build": "vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@radix-ui/react-slot": "^1.2.4", + "@tailwindcss/vite": "^4.2.2", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^1.7.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "react-router-dom": "^7.14.0", + "sonner": "^2.0.7", + "tailwind-merge": "^3.5.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.4", + "@types/node": "^24.12.2", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^4.3.4", + "autoprefixer": "^10.4.27", + "eslint": "^9.39.4", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.4.0", + "postcss": "^8.5.8", + "tailwindcss": "^4.2.2", + "typescript": "~5.9.3", + "typescript-eslint": "^8.57.0", + "vite": "^6.2.0" + } +} diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..6893eb13237060adc0c968a690149a49faa2d7d3 --- /dev/null +++ b/frontend/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/icons.svg b/frontend/public/icons.svg new file mode 100644 index 0000000000000000000000000000000000000000..5615851e102ba0b9d90688db879e9f9db99ab0fa --- /dev/null +++ b/frontend/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9a880d2485cde4737652d6ab2aea99b7e2963a96 --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,31 @@ +import { BrowserRouter, Routes, Route } from "react-router-dom" +import { Toaster } from "sonner" +import AdminLayout from "./layouts/AdminLayout" +import Dashboard from "./pages/Dashboard" +import AccountsPage from "./pages/AccountsPage" +import TestPage from "./pages/TestPage" +import TokensPage from "./pages/TokensPage" +import SettingsPage from "./pages/SettingsPage" +import ImagePage from "./pages/ImagePage" + +function App() { + return ( + <> + + + + }> + } /> + } /> + } /> + } /> + } /> + } /> + + + + + ) +} + +export default App diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx new file mode 100644 index 0000000000000000000000000000000000000000..43518ae06906aaf3a524622f2d3cb565652292ed --- /dev/null +++ b/frontend/src/components/ui/button.tsx @@ -0,0 +1,55 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: + "border border-input bg-background hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-10 px-4 py-2", + sm: "h-9 rounded-md px-3", + lg: "h-11 rounded-md px-8", + icon: "h-10 w-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + return ( + + ) + } +) +Button.displayName = "Button" + +export { Button, buttonVariants } diff --git a/frontend/src/index.css b/frontend/src/index.css new file mode 100644 index 0000000000000000000000000000000000000000..3887a39969cab4b6868be1264ecda5399a0d591a --- /dev/null +++ b/frontend/src/index.css @@ -0,0 +1,159 @@ +@import "tailwindcss"; + +@theme { + --color-border: hsl(var(--border)); + --color-input: hsl(var(--input)); + --color-ring: hsl(var(--ring)); + --color-background: hsl(var(--background)); + --color-foreground: hsl(var(--foreground)); + + --color-primary: hsl(var(--primary)); + --color-primary-foreground: hsl(var(--primary-foreground)); + + --color-secondary: hsl(var(--secondary)); + --color-secondary-foreground: hsl(var(--secondary-foreground)); + + --color-destructive: hsl(var(--destructive)); + --color-destructive-foreground: hsl(var(--destructive-foreground)); + + --color-muted: hsl(var(--muted)); + --color-muted-foreground: hsl(var(--muted-foreground)); + + --color-accent: hsl(var(--accent)); + --color-accent-foreground: hsl(var(--accent-foreground)); + + --color-popover: hsl(var(--popover)); + --color-popover-foreground: hsl(var(--popover-foreground)); + + --color-card: hsl(var(--card)); + --color-card-foreground: hsl(var(--card-foreground)); + + --radius-lg: var(--radius); + --radius-md: calc(var(--radius) - 2px); + --radius-sm: calc(var(--radius) - 4px); + + --animate-accordion-down: accordion-down 0.2s ease-out; + --animate-accordion-up: accordion-up 0.2s ease-out; + + @keyframes accordion-down { + from { + height: 0; + } + to { + height: var(--radix-accordion-content-height); + } + } + @keyframes accordion-up { + from { + height: var(--radix-accordion-content-height); + } + to { + height: 0; + } + } +} + +@utility container { + margin-inline: auto; + padding-inline: 2rem; + @media (width >= --theme(--breakpoint-sm)) { + max-width: none; + } + @media (width >= 1400px) { + max-width: 1400px; + } +} + +/* + Modern Dark Theme (Slate/Indigo) +*/ +@layer base { + :root { + /* Light theme (Brighter, cleaner, and optimized) */ + --background: 0 0% 100%; + --foreground: 240 10% 3.9%; + --card: 0 0% 100%; + --card-foreground: 240 10% 3.9%; + --popover: 0 0% 100%; + --popover-foreground: 240 10% 3.9%; + --primary: 252 80% 60%; + --primary-foreground: 0 0% 98%; + --secondary: 240 4.8% 95.9%; + --secondary-foreground: 240 5.9% 10%; + --muted: 240 4.8% 95.9%; + --muted-foreground: 240 3.8% 46.1%; + --accent: 240 4.8% 95.9%; + --accent-foreground: 240 5.9% 10%; + --destructive: 0 84.2% 60.2%; + --destructive-foreground: 0 0% 98%; + --border: 240 5.9% 90%; + --input: 240 5.9% 90%; + --ring: 252 80% 60%; + --radius: 0.75rem; + } + + @media (prefers-color-scheme: dark) { + :root { + /* Dark theme (Deep and refined) */ + --background: 240 10% 10%; + --foreground: 0 0% 98%; + --card: 240 10% 12%; + --card-foreground: 0 0% 98%; + --popover: 240 10% 12%; + --popover-foreground: 0 0% 98%; + --primary: 252 100% 75%; + --primary-foreground: 0 0% 10%; + --secondary: 240 3.7% 15.9%; + --secondary-foreground: 0 0% 98%; + --muted: 240 3.7% 15.9%; + --muted-foreground: 240 5% 64.9%; + --accent: 240 3.7% 15.9%; + --accent-foreground: 0 0% 98%; + --destructive: 0 62.8% 30.6%; + --destructive-foreground: 0 0% 98%; + --border: 240 3.7% 20%; + --input: 240 3.7% 20%; + --ring: 252 100% 75%; + } + } +} + +@layer base { + * { + @apply border-border; + } + body { + @apply bg-background text-foreground font-sans antialiased transition-colors duration-300; + } + + body::before { + content: ""; + position: fixed; + inset: 0; + z-index: -1; + background-image: + radial-gradient(circle at 15% 50%, rgba(99, 102, 241, 0.12), transparent 35%), + radial-gradient(circle at 85% 30%, rgba(168, 85, 247, 0.12), transparent 35%); + background-attachment: fixed; + pointer-events: none; + } + + @media (prefers-color-scheme: dark) { + body::before { + background-image: + radial-gradient(circle at 15% 50%, rgba(99, 102, 241, 0.08), transparent 25%), + radial-gradient(circle at 85% 30%, rgba(168, 85, 247, 0.08), transparent 25%); + } + } + + /* 修复原生 setToken(e.target.value)} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm" placeholder={"\u7c98\u8d34\u4ece Local Storage / \u672c\u5730\u5b58\u50a8 \u76f4\u63a5\u590d\u5236\u7684 token"} /> + +
+ + setEmail(e.target.value)} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm" placeholder={"\u90ae\u7bb1\u5730\u5740"} /> +
+
+ + setPassword(e.target.value)} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm" placeholder={"\u7528\u4e8e\u81ea\u52a8\u5237\u65b0\u6216\u6fc0\u6d3b"} /> +
+ + + + +
+
+

{"\u8d26\u53f7\u5217\u8868"}

+ {accounts.length} +
+ + + + + + + + + + + + {accounts.length === 0 && ( + + + + )} + {accounts.map(acc => ( + + + + + + + + ))} + +
{"\u8d26\u53f7"}{"\u72b6\u6001"}{"\u5e76\u53d1\u8d1f\u8f7d"}{"\u8bf4\u660e"}{"\u64cd\u4f5c"}
{"\u6682\u65e0\u8d26\u53f7\uff0c\u8bf7\u624b\u52a8\u6ce8\u5165\u6216\u4e00\u952e\u83b7\u53d6\u65b0\u53f7\u3002"}
{acc.email} + + {statusText(acc)} + + + + {acc.inflight || 0} {"\u7ebf\u7a0b"} + + + {statusNote(acc) || "-"} + +
+ {acc.status_code !== "valid" && acc.status_code !== "rate_limited" && acc.status_code !== "banned" && ( + + )} + + +
+
+
+ + ) +} diff --git a/frontend/src/pages/Dashboard.tsx b/frontend/src/pages/Dashboard.tsx new file mode 100644 index 0000000000000000000000000000000000000000..53d67ab80ed507a25821d3305922a634401c4295 --- /dev/null +++ b/frontend/src/pages/Dashboard.tsx @@ -0,0 +1,206 @@ +import { useEffect, useState } from "react" +import { Server, Activity, ShieldAlert, ActivityIcon, FileJson, Cpu, Shield, Globe, ImageIcon, Paperclip, Flame, Database } from "lucide-react" +import { getAuthHeader } from "../lib/auth" +import { API_BASE } from "../lib/api" +import { toast } from "sonner" + +type AccountRow = { + email: string + status: string + inflight: number + max_inflight: number + consecutive_failures: number + rate_limit_strikes: number + last_request_finished: number +} + +type Status = { + accounts?: { + total?: number + valid?: number + rate_limited?: number + invalid?: number + in_use?: number + global_in_use?: number + waiting?: number + max_inflight_per_account?: number + max_queue_size?: number + } + per_account?: AccountRow[] + chat_id_pool?: { + total_cached?: number + target_per_account?: number + ttl_seconds?: number + per_account?: Record + } | null + runtime?: { asyncio_running_tasks?: number } +} + +export default function Dashboard() { + const [status, setStatus] = useState(null) + const [errOnce, setErrOnce] = useState(false) + + useEffect(() => { + const fetchStatus = async () => { + try { + const res = await fetch(`${API_BASE}/api/admin/status`, { headers: getAuthHeader() }) + if (!res.ok) throw new Error("Unauthorized") + const data = await res.json() + setStatus(data) + } catch { + if (!errOnce) { + toast.error("状态获取失败,请在「系统设置」检查您的当前会话 Key。") + setErrOnce(true) + } + } + } + fetchStatus() + const timer = setInterval(fetchStatus, 3000) + return () => clearInterval(timer) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + const acc = status?.accounts || {} + const pool = status?.chat_id_pool + const rows = status?.per_account || [] + + return ( +
+
+
+

运行状态

+

全局并发监控与千问账号池概览(每 3 秒自动刷新)。

+
+ +
+ } title="可用账号" value={String(acc.valid ?? 0)} accent="primary" sub={`共 ${acc.total ?? 0} 个`} /> + } title="当前并发" value={String(acc.in_use ?? 0)} accent="blue" sub={`全局上限 ${acc.global_in_use ?? 0}`} /> + } title="排队请求" value={String(acc.waiting ?? 0)} accent="destructive" sub={`队列上限 ${acc.max_queue_size ?? 0}`} /> + } title="限流号/失效号" value={`${acc.rate_limited ?? 0} / ${acc.invalid ?? 0}`} accent="orange" /> +
+ +
+ } title="Chat_ID 预热池" value={String(pool?.total_cached ?? 0)} accent="rose" sub={pool ? `每账号目标 ${pool.target_per_account} · TTL ${Math.round((pool.ttl_seconds || 0) / 60)} 分钟` : "未启用"} /> + } title="异步任务" value={String(status?.runtime?.asyncio_running_tasks ?? 0)} accent="cyan" sub="asyncio active task count" /> +
+ + {rows.length > 0 && ( +
+
+
+

+ + 账号并发详情 +

+
+
+ + + + + + + + + + + + + {rows.map(r => { + const warmSize = pool?.per_account?.[r.email] ?? 0 + const badge = r.status === "valid" ? "bg-emerald-500/15 text-emerald-300 ring-emerald-500/30" + : r.status === "rate_limited" ? "bg-orange-500/15 text-orange-300 ring-orange-500/30" + : "bg-red-500/15 text-red-300 ring-red-500/30" + return ( + + + + + + + + + ) + })} + +
邮箱状态在途预热 chat_id连失限流次
{r.email} + {r.status} + + {r.inflight}/{r.max_inflight} + + {warmSize} + {r.consecutive_failures}{r.rate_limit_strikes}
+
+
+ )} + +
+
+
+

+ + API 接口池 +

+

兼容主流 AI 协议的调用入口,默认无需认证,或通过 API Key 访问。

+
+
+
+ } iconBg="bg-emerald-500/10" path="POST /v1/chat/completions" tag="OpenAI" tagColor="emerald" /> + } iconBg="bg-blue-500/10" path="POST /v1/messages" tag="Anthropic" tagColor="blue" /> + } iconBg="bg-yellow-500/10" path="POST /v1/models/gemini-pro:generateContent" tag="Gemini" tagColor="yellow" /> + } iconBg="bg-purple-500/10" path="POST /v1/images/generations" tag="Image Gen" tagColor="purple" /> + } iconBg="bg-cyan-500/10" path="POST /v1/files" tag="Files" tagColor="cyan" /> + } iconBg="bg-slate-500/10" path="GET /" tag="健康检查" tagColor="slate" /> +
+
+
+
+ ) +} + +function StatCard({ icon, title, value, accent, sub }: { icon: React.ReactNode; title: string; value: string; accent: string; sub?: string }) { + const shadowMap: Record = { + primary: "hover:shadow-primary/5", + blue: "hover:shadow-blue-500/5", + destructive: "hover:shadow-destructive/10", + orange: "hover:shadow-orange-500/5", + rose: "hover:shadow-rose-500/5", + cyan: "hover:shadow-cyan-500/5", + } + const gradMap: Record = { + primary: "from-primary/10", + blue: "from-blue-500/10", + destructive: "from-destructive/10", + orange: "from-orange-500/10", + rose: "from-rose-500/10", + cyan: "from-cyan-500/10", + } + return ( +
+
+
+
+

{title}

+
{icon}
+
+
+ {value} +
+ {sub ?
{sub}
: null} +
+
+ ) +} + +function EndpointRow({ icon, iconBg, path, tag, tagColor }: { icon: React.ReactNode; iconBg: string; path: string; tag: string; tagColor: string }) { + const tagClass = `bg-${tagColor}-500/10 text-${tagColor}-600 dark:bg-${tagColor}-500/20 dark:text-${tagColor}-300 ring-1 ring-${tagColor}-500/20 dark:ring-${tagColor}-500/30` + return ( +
+
+
{icon}
+
{path}
+
+ {tag} +
+ ) +} diff --git a/frontend/src/pages/ImagePage.tsx b/frontend/src/pages/ImagePage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..958989b0df720bb39a567c131f7fe6defd2ac33d --- /dev/null +++ b/frontend/src/pages/ImagePage.tsx @@ -0,0 +1,274 @@ +import { useState } from "react" +import { Image as ImageIcon, RefreshCw, Download, Wand2 } from "lucide-react" +import { Button } from "../components/ui/button" +import { toast } from "sonner" +import { getAuthHeader } from "../lib/auth" +import { API_BASE } from "../lib/api" + +const ASPECT_RATIOS = [ + { label: "1:1", value: "1:1", w: 1024, h: 1024 }, + { label: "16:9", value: "16:9", w: 1024, h: 576 }, + { label: "9:16", value: "9:16", w: 576, h: 1024 }, + { label: "4:3", value: "4:3", w: 1024, h: 768 }, + { label: "3:4", value: "3:4", w: 768, h: 1024 }, +] + +interface GeneratedImage { + url: string + revised_prompt: string + ratio: string +} + +export default function ImagePage() { + const [prompt, setPrompt] = useState("") + const [ratio, setRatio] = useState("1:1") + const [n, setN] = useState(1) + const [loading, setLoading] = useState(false) + const [images, setImages] = useState([]) + const [error, setError] = useState(null) + + const selectedRatio = ASPECT_RATIOS.find(r => r.value === ratio)! + const sizeStr = `${selectedRatio.w}x${selectedRatio.h}` + + const handleGenerate = async () => { + if (!prompt.trim() || loading) return + setLoading(true) + setError(null) + + try { + const res = await fetch(`${API_BASE}/v1/images/generations`, { + method: "POST", + headers: { "Content-Type": "application/json", ...getAuthHeader() }, + body: JSON.stringify({ + model: "dall-e-3", + prompt: prompt.trim(), + n, + size: sizeStr, + response_format: "url", + }), + }) + + const data = await res.json() + if (!res.ok) { + const detail = data?.detail || data?.error || `HTTP ${res.status}` + setError(String(detail)) + toast.error(`生成失败: ${String(detail).slice(0, 80)}`) + return + } + + const newImages: GeneratedImage[] = (data.data || []).map((item: any) => ({ + url: item.url, + revised_prompt: item.revised_prompt || prompt, + ratio, + })) + + if (newImages.length === 0) { + setError("未返回图片,请重试") + toast.error("未返回图片,请重试") + return + } + + setImages(prev => [...newImages, ...prev]) + toast.success(`成功生成 ${newImages.length} 张图片`) + } catch (err: any) { + const msg = err.message || "网络错误" + setError(msg) + toast.error(`生成失败: ${msg}`) + } finally { + setLoading(false) + } + } + + const handleDownload = (url: string, idx: number) => { + const a = document.createElement("a") + a.href = url + a.download = `qwen_image_${Date.now()}_${idx}.png` + a.target = "_blank" + a.rel = "noopener noreferrer" + a.click() + } + + return ( +
+
+

图片生成

+

通过 Qwen3.6-Plus 生成 AI 图片,支持多种比例。

+
+ + {/* 输入区域 */} +
+
+ + - Token 不会写入磁盘,也不会显示在结果中。 -
- -
-
- - - 用于 Checkout、Stripe、税务、PaymentMethod、confirm、approve 和最终 iDEAL 跳转。 -
-
- - - 只用于同一个 Checkout 的 Promotion Update,完成后立即切回本轮 Checkout 代理。 -
-
- - - -
- - - 两个代理池都必须填写。 -
- - - -
-
提取进度准备
-
-
- -
-
- 打开 iDEAL 链 - -
-
-
-
-
- - - - - - diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index d07c4d2d877298073cc311990a3163285a2b255b..0000000000000000000000000000000000000000 --- a/src/lib.rs +++ /dev/null @@ -1,7316 +0,0 @@ -use async_trait::async_trait; -use axum::{ - extract::{Path, Query, State}, - http::{header, HeaderMap, HeaderValue, StatusCode}, - response::{Html, IntoResponse, Redirect, Response}, - routing::{get, post}, - Json, Router, -}; -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; -use regex::Regex; -use reqwest::redirect::Policy; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; -use sqlx::{postgres::PgPoolOptions, PgPool}; -use std::{ - collections::BTreeMap, - env, fs, - io::ErrorKind, - path::{Path as FsPath, PathBuf}, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, - Arc, Mutex as StdMutex, OnceLock, - }, - time::{Duration, SystemTime, UNIX_EPOCH}, -}; -use tokio::sync::{mpsc, Mutex as TokioMutex}; -use url::{Host, Url}; -use uuid::Uuid; - -pub const DEFAULT_STRIPE_PK: &str = "pk_REDACTED"; -pub const STRIPE_VERSION_FULL: &str = - "2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"; -pub const PAYPAL_STRIPE_VERSION: &str = - "2020-08-27;custom_checkout_beta=v1; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"; -pub const DEFAULT_STRIPE_RUNTIME_VERSION: &str = "6f8494a281"; -pub const PAYPAL_STRIPE_RUNTIME_VERSION: &str = "81274c9437"; -pub const APPLE_SAFARI_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15"; -pub const PAYPAL_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/IP_REDACTED Safari/537.36"; -pub const CHATGPT_CLIENT_VERSION: &str = "prod-db390ebea64862bf1899c420a4c736e0cf639747"; -pub const CHATGPT_CLIENT_BUILD_NUMBER: &str = "7904904"; - -const ACCEPT_LANGUAGE: &str = "nl-NL,nl;q=0.9,en;q=0.8"; -const BROWSER_LOCALE: &str = "nl-NL"; -const ELEMENTS_LOCALE: &str = "nl"; -const BROWSER_TIMEZONE: &str = "Europe/Amsterdam"; -const IDEAL_BILLING_NAME: &str = "Jan de Vries"; -const IDEAL_BILLING_LINE1: &str = "Prinsengracht 263"; -const IDEAL_BILLING_CITY: &str = "Amsterdam"; -const IDEAL_BILLING_POSTAL_CODE: &str = "1016 GV"; -// iDEAL's allowed payment-method list is fixed when Stripe Checkout is -// created. Create the session through NL so iDEAL is present, then send the -// official ChatGPT checkout/update request through VN to apply the regional -// promotion, and finally return to NL for Stripe and approval. -const CHECKOUT_REGION: &str = "NL"; -const PROMOTION_REGION: &str = "VN"; -const PROVIDER_REGION: &str = "NL"; -const APPROVE_REGION: &str = "NL"; -const PAYPAL_ACCEPT_LANGUAGE: &str = "pt-BR,pt;q=0.9,en;q=0.8"; -const PAYPAL_BROWSER_LOCALE: &str = "pt-BR"; -const PAYPAL_ELEMENTS_LOCALE: &str = "pt-BR"; -const PAYPAL_BROWSER_TIMEZONE: &str = "America/Sao_Paulo"; -const PAYPAL_CHECKOUT_REGION: &str = "US"; -const PAYPAL_PROMOTION_REGION: &str = "VN"; -const PAYPAL_PROVIDER_REGION: &str = "TR"; -const PAYPAL_APPROVE_REGION: &str = "US"; -const PAYPAL_BILLING_COUNTRY: &str = "US"; -const PAYPAL_BILLING_STATE: &str = "CA"; -const MAX_APPROVE_ATTEMPTS: usize = 20; -const PAYPAL_APPROVE_MAX_ATTEMPTS: usize = 1; -const APPROVE_CONCURRENCY: usize = 1; -const MAX_REBUILD_ATTEMPTS: usize = 5; -const PAYPAL_PROVIDER_MAX_ATTEMPTS: usize = 10; -const IDEAL_REDIRECT_POLL_ATTEMPTS: usize = MAX_APPROVE_ATTEMPTS; -const PAYPAL_REDIRECT_POLL_ATTEMPTS: usize = 45; -const APPROVED_REDIRECT_POLL_ATTEMPTS: usize = 1; -const DEFAULT_PROXY_ENV: &str = "OPENAI_PAY_DEFAULT_PROXY"; -const QUEUE_CONFIG_FILE: &str = "queue-config.json"; -const RUN_OUTPUT_DIR: &str = "run-output"; -const APPROVED_PROXY_CACHE_FILE: &str = "run-output/approved-proxies.json"; -const FINGERPRINT_DATA_DIR: &str = "data"; -const FINGERPRINT_LEGACY_DIR: &str = "run-logs"; -const DEFAULT_EXTRACT_WORKERS: usize = 100; -const DEFAULT_EXTRACT_QUEUE_CAPACITY: usize = 1000; -const MIN_FINISHED_JOB_RETAINED: usize = 80; -const DATABASE_URL_ENV: &str = "DATABASE_URL"; -const DEFAULT_CDK_USES: usize = 10; -const ANONYMOUS_CDK_USER_PREFIX: &str = "cdk:"; -const SESSION_COOKIE_NAME: &str = "ideal_linuxdo_session"; -const OAUTH_STATE_COOKIE_NAME: &str = "ideal_linuxdo_oauth_state"; -const SESSION_TTL_SECS: i64 = 30 * 24 * 60 * 60; -const LINUXDO_CLIENT_ID_ENV: &str = "LINUXDO_CLIENT_ID"; -const LINUXDO_CLIENT_SECRET_ENV: &str = "LINUXDO_CLIENT_SECRET"; -const LINUXDO_REDIRECT_URI_ENV: &str = "LINUXDO_REDIRECT_URI"; -const LINUXDO_AUTH_URL: &str = "https://connect.linux.do/oauth2/authorize"; -const LINUXDO_TOKEN_URL: &str = "https://connect.linux.do/oauth2/token"; -const LINUXDO_USERINFO_URL: &str = "https://connect.linux.do/api/user"; -const OAUTH_STATE_TTL_SECS: u64 = 600; -const MAX_OAUTH_STATES: usize = 512; - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct LockedConfig { - pub link_type: &'static str, - pub billing_country: &'static str, - pub currency: &'static str, - pub checkout_ui_mode: &'static str, - pub payment_locale: &'static str, - pub client_fingerprint: &'static str, - pub user_agent: &'static str, - pub checkout_proxy_region: &'static str, - #[serde(skip_serializing_if = "Option::is_none")] - pub promotion_proxy_region: Option<&'static str>, - pub provider_proxy_region: &'static str, - pub approve_proxy_region: &'static str, - pub approve_max_attempts: usize, - pub approve_concurrency: usize, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum LinkType { - Ideal, - Paypal, -} - -impl LinkType { - fn parse(value: &str) -> Result { - match value.trim().to_ascii_lowercase().as_str() { - "" | "ideal" => Ok(Self::Ideal), - "paypal" | "pp" => Ok(Self::Paypal), - other => Err(ExtractError::BadResponse(format!( - "unsupported link_type: {other}" - ))), - } - } - - const fn as_str(self) -> &'static str { - match self { - Self::Ideal => "ideal", - Self::Paypal => "paypal", - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ExtractInput { - pub access_token: String, - pub proxy: String, - pub checkout_proxy_pool: Vec, - pub promotion_proxy_pool: Vec, - pub paypal_provider_proxy_pool: Vec, - pub base_url: String, - pub link_type: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExtractApiInput { - pub access_token: String, - #[serde(default)] - pub link_type: Option, - #[serde(default)] - pub checkout_proxy_pool: String, - #[serde(default)] - pub promotion_proxy_pool: String, - #[serde(default)] - pub paypal_checkout_proxy_pool: String, - #[serde(default)] - pub paypal_promotion_proxy_pool: String, - #[serde(default)] - pub paypal_provider_proxy_pool: String, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct Step { - pub name: String, - pub status: String, - pub detail: String, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct ExtractOutput { - pub ok: bool, - pub cs_id: String, - pub billing_country: String, - pub currency: String, - pub payment_method_id: String, - pub stripe_redirect_url: String, - pub provider_redirect_url: String, - pub long_url: String, - pub amount: String, - pub amount_display: String, - #[serde(default)] - pub fallback: bool, - #[serde(default)] - pub provider_error: String, - pub config: LockedConfig, - pub steps: Vec, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct ExtractApiResponse { - pub ok: bool, - pub output: Option, - pub error: Option, - pub job: Option, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct AuthApiResponse { - pub ok: bool, - pub user: Option, - pub error: Option, - pub login_url: Option, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct AuthUserSnapshot { - pub linuxdo_id: String, - pub username: String, - pub display_name: String, - pub cdk: String, - pub total_uses: usize, - pub remaining_uses: usize, - pub pending_uses: usize, - pub available_uses: usize, -} - -#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] -pub struct BindCdkInput { - pub cdk: String, -} - -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ExtractJobStatus { - Queued, - Running, - Completed, - Failed, - Canceled, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct ExtractJobSnapshot { - pub job_id: String, - pub status: ExtractJobStatus, - pub position: usize, - pub queue_size: usize, - pub steps: Vec, - pub output: Option, - pub error: Option, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] -pub struct QueueConfig { - #[serde(default = "default_extract_workers")] - pub worker_count: usize, - #[serde(default = "default_extract_queue_capacity")] - pub queue_capacity: usize, -} - -impl QueueConfig { - fn normalized(self) -> Self { - Self { - worker_count: self.worker_count.max(1), - queue_capacity: self.queue_capacity.max(1), - } - } - - fn finished_job_retained(self) -> usize { - let config = self.normalized(); - config - .worker_count - .saturating_add(config.queue_capacity) - .max(MIN_FINISHED_JOB_RETAINED) - } -} - -impl Default for QueueConfig { - fn default() -> Self { - Self { - worker_count: default_extract_workers(), - queue_capacity: default_extract_queue_capacity(), - } - } -} - -fn default_extract_workers() -> usize { - DEFAULT_EXTRACT_WORKERS -} - -fn default_extract_queue_capacity() -> usize { - DEFAULT_EXTRACT_QUEUE_CAPACITY -} - -fn configured_queue_config() -> QueueConfig { - configured_queue_config_from_path(FsPath::new(QUEUE_CONFIG_FILE)) -} - -fn configured_queue_config_from_path(path: &FsPath) -> QueueConfig { - match fs::read_to_string(path) { - Ok(text) => queue_config_from_json(&text).unwrap_or_default(), - Err(error) if error.kind() == ErrorKind::NotFound => { - let config = QueueConfig::default(); - let _ = fs::write(path, queue_config_json(config)); - config - } - Err(_) => QueueConfig::default(), - } -} - -fn queue_config_from_json(text: &str) -> Result { - serde_json::from_str::(text).map(QueueConfig::normalized) -} - -fn queue_config_json(config: QueueConfig) -> String { - format!( - "{}\n", - serde_json::to_string_pretty(&config.normalized()).expect("queue config should serialize") - ) -} - -#[derive(Clone)] -struct AuthStore { - pool: PgPool, -} - -#[derive(Debug, Clone, Copy, Default)] -struct OAuthStateRecord { - created_at_secs: u64, -} - -#[derive(Debug, Clone)] -struct AuthUserRecord { - linuxdo_id: String, - username: String, - display_name: String, - cdk: String, - total_uses: usize, - remaining_uses: usize, - pending_uses: usize, -} - -#[derive(Debug, Clone, Deserialize)] -pub struct LinuxDoCallbackQuery { - code: Option, - state: Option, - error: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct LinuxDoTokenResponse { - access_token: String, -} - -#[derive(Debug, Clone, Deserialize)] -struct LinuxDoUserInfo { - id: Value, - #[serde(default)] - username: String, - #[serde(default)] - name: String, - #[serde(default)] - active: bool, - #[serde(default)] - trust_level: i64, - #[serde(default)] - silenced: bool, -} - -#[derive(Debug, Clone)] -struct LinuxDoOAuthConfig { - client_id: String, - client_secret: String, - redirect_uri: String, - auth_url: String, - token_url: String, - user_url: String, - min_trust_level: i64, -} - -#[derive(Debug, thiserror::Error)] -enum AuthError { - #[error("请先输入 CDK。")] - Unauthorized, - #[error("CDK 使用次数已用完。")] - NoQuota, - #[error("LinuxDo OAuth 未配置。")] - OAuthNotConfigured, - #[error("CDK 不能为空。")] - MissingCdk, - #[error("当前 CDK 仍有剩余额度或进行中任务,暂不能绑定新 CDK。")] - CdkNotReady, - #[error("CDK 不存在或已被绑定。")] - CdkUnavailable, - #[error("数据库暂不可用。")] - Database, - #[error("LinuxDo 授权失败:{0}")] - OAuth(String), - #[error("LinuxDo 账号未启用。")] - InactiveAccount, - #[error("LinuxDo 账号已被禁言,无法使用。")] - SilencedAccount, - #[error("LinuxDo 账号信任等级不足,当前 {current},需要 {required}。")] - TrustLevel { required: i64, current: i64 }, -} - -impl AuthStore { - async fn new_from_env() -> Self { - let database_url = configured_database_url() - .unwrap_or_else(|| panic!("{DATABASE_URL_ENV} is required for production storage")); - let pool = PgPoolOptions::new() - .max_connections(10) - .connect(&database_url) - .await - .unwrap_or_else(|error| panic!("failed to connect PostgreSQL: {error}")); - migrate_auth_store(&pool) - .await - .unwrap_or_else(|error| panic!("failed to migrate PostgreSQL auth store: {error}")); - clear_stale_pending_uses(&pool) - .await - .unwrap_or_else(|error| panic!("failed to clear stale pending CDK uses: {error}")); - Self { pool } - } - - async fn user_from_headers(&self, headers: &HeaderMap) -> Result { - let session = cookie_value(headers, SESSION_COOKIE_NAME).ok_or(AuthError::Unauthorized)?; - self.user_from_session(&session) - .await? - .ok_or(AuthError::Unauthorized) - } - - async fn user_from_session( - &self, - session: &str, - ) -> Result, AuthError> { - self.prune_expired_sessions().await?; - let linuxdo_id = sqlx::query_scalar::<_, String>( - "SELECT linuxdo_id FROM auth_sessions - WHERE session = $1 - AND created_at > now() - ($2::bigint * INTERVAL '1 second')", - ) - .bind(session) - .bind(SESSION_TTL_SECS) - .fetch_optional(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - match linuxdo_id { - Some(linuxdo_id) => self.user_by_id(&linuxdo_id).await, - None => Ok(None), - } - } - - async fn login_cdk_user(&self, cdk: &str) -> Result<(String, AuthUserSnapshot), AuthError> { - let cdk = normalize_cdk(cdk)?; - let session = Uuid::new_v4().to_string(); - let mut tx = self.pool.begin().await.map_err(|_| AuthError::Database)?; - let candidate = sqlx::query_as::<_, (String, Option, bool, i32, i32, i32)>( - "SELECT cdk, linuxdo_id, active, total_uses, remaining_uses, pending_uses - FROM auth_cdks - WHERE cdk = $1 - FOR UPDATE", - ) - .bind(&cdk) - .fetch_optional(&mut *tx) - .await - .map_err(|_| AuthError::Database)? - .ok_or(AuthError::CdkUnavailable)?; - - let (cdk, linuxdo_id, active, _total_uses, remaining_uses, _pending_uses) = candidate; - let linuxdo_id = match linuxdo_id { - Some(linuxdo_id) => { - if !active { - return Err(AuthError::CdkUnavailable); - } - if linuxdo_id.starts_with(ANONYMOUS_CDK_USER_PREFIX) { - sqlx::query( - "UPDATE auth_users - SET username = $2, - display_name = $3, - active = true, - silenced = false, - updated_at = now() - WHERE linuxdo_id = $1", - ) - .bind(&linuxdo_id) - .bind("cdk-user") - .bind(anonymous_cdk_display_name(&cdk)) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - } - linuxdo_id - } - None => { - if active { - return Err(AuthError::CdkUnavailable); - } - if remaining_uses <= 0 { - return Err(AuthError::NoQuota); - } - let linuxdo_id = anonymous_cdk_user_id(&cdk); - let display_name = anonymous_cdk_display_name(&cdk); - sqlx::query( - "INSERT INTO auth_users (linuxdo_id, username, display_name, trust_level, active, silenced, updated_at) - VALUES ($1, $2, $3, 0, true, false, now()) - ON CONFLICT (linuxdo_id) DO UPDATE SET - username = EXCLUDED.username, - display_name = EXCLUDED.display_name, - trust_level = EXCLUDED.trust_level, - active = EXCLUDED.active, - silenced = EXCLUDED.silenced, - updated_at = now()", - ) - .bind(&linuxdo_id) - .bind("cdk-user") - .bind(&display_name) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - sqlx::query( - "UPDATE auth_cdks - SET linuxdo_id = $1, active = true, bound_at = COALESCE(bound_at, now()) - WHERE cdk = $2", - ) - .bind(&linuxdo_id) - .bind(&cdk) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - linuxdo_id - } - }; - - sqlx::query("INSERT INTO auth_sessions (session, linuxdo_id) VALUES ($1, $2)") - .bind(&session) - .bind(&linuxdo_id) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - tx.commit().await.map_err(|_| AuthError::Database)?; - let snapshot = self - .user_by_id(&linuxdo_id) - .await? - .ok_or(AuthError::Unauthorized)?; - Ok((session, snapshot)) - } - - async fn create_oauth_state(&self) -> Result { - let state = Uuid::new_v4().simple().to_string(); - let now = now_epoch_secs(); - self.prune_oauth_states().await?; - sqlx::query("INSERT INTO oauth_states (state, created_at_secs) VALUES ($1, $2)") - .bind(&state) - .bind(now as i64) - .execute(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - self.trim_oauth_states_to_cap().await?; - Ok(state) - } - - async fn consume_oauth_state(&self, state: &str) -> Result { - self.prune_oauth_states().await?; - let row = sqlx::query_as::<_, (i64,)>( - "DELETE FROM oauth_states WHERE state = $1 RETURNING created_at_secs", - ) - .bind(state) - .fetch_optional(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - Ok(row - .map(|(created_at_secs,)| { - !oauth_state_is_expired( - OAuthStateRecord { - created_at_secs: created_at_secs.max(0) as u64, - }, - now_epoch_secs(), - ) - }) - .unwrap_or(false)) - } - - async fn login_linuxdo_user( - &self, - user: LinuxDoUserInfo, - min_trust_level: i64, - ) -> Result<(String, AuthUserSnapshot), AuthError> { - let linuxdo_id = linuxdo_id_string(&user.id) - .ok_or_else(|| AuthError::OAuth("LinuxDo 没有返回用户 ID。".to_string()))?; - let username = user.username; - let display_name = user_display_name(&username, &user.name); - let trust_level = user.trust_level; - let active = user.active; - let silenced = user.silenced; - let session = Uuid::new_v4().to_string(); - let mut tx = self.pool.begin().await.map_err(|_| AuthError::Database)?; - sqlx::query( - "INSERT INTO auth_users (linuxdo_id, username, display_name, trust_level, active, silenced, updated_at) - VALUES ($1, $2, $3, $4, $5, $6, now()) - ON CONFLICT (linuxdo_id) DO UPDATE SET - username = EXCLUDED.username, - display_name = EXCLUDED.display_name, - trust_level = EXCLUDED.trust_level, - active = EXCLUDED.active, - silenced = EXCLUDED.silenced, - updated_at = now()", - ) - .bind(&linuxdo_id) - .bind(&username) - .bind(&display_name) - .bind(trust_level) - .bind(active) - .bind(silenced) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - if let Some(error) = linuxdo_account_error(active, silenced, trust_level, min_trust_level) { - sqlx::query("DELETE FROM auth_sessions WHERE linuxdo_id = $1") - .bind(&linuxdo_id) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - tx.commit().await.map_err(|_| AuthError::Database)?; - return Err(error); - } - let active_cdk = sqlx::query_as::<_, (String,)>( - "SELECT cdk FROM auth_cdks WHERE linuxdo_id = $1 AND active = true LIMIT 1", - ) - .bind(&linuxdo_id) - .fetch_optional(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - if active_cdk.is_none() { - sqlx::query( - "INSERT INTO auth_cdks (cdk, linuxdo_id, kind, total_uses, remaining_uses, pending_uses, active, bound_at) - VALUES ($1, $2, 'auto', $3, $3, 0, true, now())", - ) - .bind(new_cdk()) - .bind(&linuxdo_id) - .bind(DEFAULT_CDK_USES as i32) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - } - sqlx::query("INSERT INTO auth_sessions (session, linuxdo_id) VALUES ($1, $2)") - .bind(&session) - .bind(&linuxdo_id) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - tx.commit().await.map_err(|_| AuthError::Database)?; - let snapshot = self - .user_by_id(&linuxdo_id) - .await? - .ok_or(AuthError::Unauthorized)?; - Ok((session, snapshot)) - } - - async fn logout(&self, session: &str) -> Result<(), AuthError> { - sqlx::query("DELETE FROM auth_sessions WHERE session = $1") - .bind(session) - .execute(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - Ok(()) - } - - async fn reserve_use(&self, linuxdo_id: &str) -> Result { - let mut tx = self.pool.begin().await.map_err(|_| AuthError::Database)?; - let row = active_cdk_row_for_update(&mut tx, linuxdo_id).await?; - let Some((cdk, _, remaining_uses, pending_uses)) = row else { - return Err(AuthError::Unauthorized); - }; - if available_uses(remaining_uses, pending_uses) == 0 { - return Err(AuthError::NoQuota); - } - sqlx::query("UPDATE auth_cdks SET pending_uses = pending_uses + 1 WHERE cdk = $1") - .bind(cdk) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - tx.commit().await.map_err(|_| AuthError::Database)?; - self.user_by_id(linuxdo_id) - .await? - .ok_or(AuthError::Unauthorized) - } - - async fn release_reserved_use(&self, linuxdo_id: &str) { - let _ = sqlx::query( - "UPDATE auth_cdks SET pending_uses = GREATEST(pending_uses - 1, 0) - WHERE linuxdo_id = $1 AND active = true", - ) - .bind(linuxdo_id) - .execute(&self.pool) - .await; - } - - async fn complete_reserved_use(&self, linuxdo_id: &str, success: bool) { - let _ = sqlx::query( - "UPDATE auth_cdks SET - pending_uses = GREATEST(pending_uses - 1, 0), - remaining_uses = CASE WHEN $2 THEN GREATEST(remaining_uses - 1, 0) ELSE remaining_uses END - WHERE linuxdo_id = $1 AND active = true", - ) - .bind(linuxdo_id) - .bind(success) - .execute(&self.pool) - .await; - } - - async fn bind_cdk(&self, linuxdo_id: &str, cdk: &str) -> Result { - let cdk = normalize_cdk(cdk)?; - let mut tx = self.pool.begin().await.map_err(|_| AuthError::Database)?; - let active = active_cdk_row_for_update(&mut tx, linuxdo_id) - .await? - .ok_or(AuthError::Unauthorized)?; - let (_, _, remaining_uses, pending_uses) = active; - if remaining_uses > 0 || pending_uses > 0 { - return Err(AuthError::CdkNotReady); - } - let candidate = sqlx::query_as::<_, (String, Option, bool)>( - "SELECT cdk, linuxdo_id, active FROM auth_cdks WHERE cdk = $1 FOR UPDATE", - ) - .bind(&cdk) - .fetch_optional(&mut *tx) - .await - .map_err(|_| AuthError::Database)? - .ok_or(AuthError::CdkUnavailable)?; - if candidate.1.is_some() || candidate.2 { - return Err(AuthError::CdkUnavailable); - } - sqlx::query("UPDATE auth_cdks SET active = false WHERE linuxdo_id = $1 AND active = true") - .bind(linuxdo_id) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - sqlx::query( - "UPDATE auth_cdks SET linuxdo_id = $1, active = true, bound_at = now() WHERE cdk = $2", - ) - .bind(linuxdo_id) - .bind(&cdk) - .execute(&mut *tx) - .await - .map_err(|_| AuthError::Database)?; - tx.commit().await.map_err(|_| AuthError::Database)?; - self.user_by_id(linuxdo_id) - .await? - .ok_or(AuthError::Unauthorized) - } - - async fn user_by_id(&self, linuxdo_id: &str) -> Result, AuthError> { - let row = sqlx::query_as::<_, (String, String, String, String, i32, i32, i32)>( - "SELECT u.linuxdo_id, u.username, u.display_name, - c.cdk, c.total_uses, c.remaining_uses, c.pending_uses - FROM auth_users u - JOIN auth_cdks c ON c.linuxdo_id = u.linuxdo_id AND c.active = true - WHERE u.linuxdo_id = $1 - AND u.active = true - AND u.silenced = false - AND u.trust_level >= $2", - ) - .bind(linuxdo_id) - .bind(configured_min_trust_level()) - .fetch_optional(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - Ok(row.map(auth_user_from_row).map(|record| record.snapshot())) - } - - async fn prune_expired_sessions(&self) -> Result<(), AuthError> { - sqlx::query( - "DELETE FROM auth_sessions - WHERE created_at <= now() - ($1::bigint * INTERVAL '1 second')", - ) - .bind(SESSION_TTL_SECS) - .execute(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - Ok(()) - } - - async fn prune_oauth_states(&self) -> Result<(), AuthError> { - let cutoff = now_epoch_secs().saturating_sub(OAUTH_STATE_TTL_SECS) as i64; - sqlx::query("DELETE FROM oauth_states WHERE created_at_secs < $1") - .bind(cutoff) - .execute(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - Ok(()) - } - - async fn trim_oauth_states_to_cap(&self) -> Result<(), AuthError> { - sqlx::query( - "DELETE FROM oauth_states - WHERE state IN ( - SELECT state FROM oauth_states - ORDER BY created_at_secs DESC - OFFSET $1 - )", - ) - .bind(MAX_OAUTH_STATES as i64) - .execute(&self.pool) - .await - .map_err(|_| AuthError::Database)?; - Ok(()) - } -} - -fn configured_database_url() -> Option { - env::var(DATABASE_URL_ENV) - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) - .or_else(|| { - fs::read_to_string(".env") - .ok() - .and_then(|text| env_value_from_text(&text, DATABASE_URL_ENV)) - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) - }) -} - -async fn active_cdk_row_for_update( - tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, - linuxdo_id: &str, -) -> Result, AuthError> { - sqlx::query_as::<_, (String, i32, i32, i32)>( - "SELECT cdk, total_uses, remaining_uses, pending_uses - FROM auth_cdks - WHERE linuxdo_id = $1 AND active = true - FOR UPDATE", - ) - .bind(linuxdo_id) - .fetch_optional(&mut **tx) - .await - .map_err(|_| AuthError::Database) -} - -async fn migrate_auth_store(pool: &PgPool) -> Result<(), sqlx::Error> { - sqlx::query( - "CREATE TABLE IF NOT EXISTS auth_users ( - linuxdo_id TEXT PRIMARY KEY, - username TEXT NOT NULL, - display_name TEXT NOT NULL, - trust_level BIGINT NOT NULL, - active BOOLEAN NOT NULL, - silenced BOOLEAN NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT now() - )", - ) - .execute(pool) - .await?; - sqlx::query( - "CREATE TABLE IF NOT EXISTS auth_cdks ( - cdk TEXT PRIMARY KEY, - linuxdo_id TEXT REFERENCES auth_users(linuxdo_id) ON DELETE SET NULL, - kind TEXT NOT NULL DEFAULT 'external', - total_uses INTEGER NOT NULL DEFAULT 10 CHECK (total_uses >= 0), - remaining_uses INTEGER NOT NULL DEFAULT 10 CHECK (remaining_uses >= 0), - pending_uses INTEGER NOT NULL DEFAULT 0 CHECK (pending_uses >= 0), - active BOOLEAN NOT NULL DEFAULT false, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - bound_at TIMESTAMPTZ - )", - ) - .execute(pool) - .await?; - sqlx::query( - "CREATE UNIQUE INDEX IF NOT EXISTS auth_cdks_one_active_per_user - ON auth_cdks(linuxdo_id) - WHERE active = true AND linuxdo_id IS NOT NULL", - ) - .execute(pool) - .await?; - sqlx::query( - "CREATE TABLE IF NOT EXISTS auth_sessions ( - session TEXT PRIMARY KEY, - linuxdo_id TEXT NOT NULL REFERENCES auth_users(linuxdo_id) ON DELETE CASCADE, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() - )", - ) - .execute(pool) - .await?; - sqlx::query( - "CREATE TABLE IF NOT EXISTS oauth_states ( - state TEXT PRIMARY KEY, - created_at_secs BIGINT NOT NULL - )", - ) - .execute(pool) - .await?; - Ok(()) -} - -async fn clear_stale_pending_uses(pool: &PgPool) -> Result<(), sqlx::Error> { - sqlx::query("UPDATE auth_cdks SET pending_uses = 0 WHERE pending_uses > 0") - .execute(pool) - .await?; - Ok(()) -} - -fn auth_user_from_row(row: (String, String, String, String, i32, i32, i32)) -> AuthUserRecord { - AuthUserRecord { - linuxdo_id: row.0, - username: row.1, - display_name: row.2, - cdk: row.3, - total_uses: row.4.max(0) as usize, - remaining_uses: row.5.max(0) as usize, - pending_uses: row.6.max(0) as usize, - } -} - -fn available_uses(remaining_uses: i32, pending_uses: i32) -> usize { - (remaining_uses.max(0) as usize).saturating_sub(pending_uses.max(0) as usize) -} - -impl AuthUserRecord { - fn available_uses(&self) -> usize { - self.remaining_uses.saturating_sub(self.pending_uses) - } - - fn snapshot(&self) -> AuthUserSnapshot { - AuthUserSnapshot { - linuxdo_id: self.linuxdo_id.clone(), - username: self.username.clone(), - display_name: self.display_name.clone(), - cdk: self.cdk.clone(), - total_uses: self.total_uses, - remaining_uses: self.remaining_uses, - pending_uses: self.pending_uses, - available_uses: self.available_uses(), - } - } -} - -fn oauth_state_is_expired(record: OAuthStateRecord, now: u64) -> bool { - now.saturating_sub(record.created_at_secs) > OAUTH_STATE_TTL_SECS -} - -fn now_epoch_secs() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system clock must be after unix epoch") - .as_secs() -} - -fn linuxdo_id_string(value: &Value) -> Option { - value - .as_i64() - .map(|value| value.to_string()) - .or_else(|| value.as_u64().map(|value| value.to_string())) - .or_else(|| value.as_str().map(str::trim).map(ToOwned::to_owned)) - .filter(|value| !value.is_empty()) -} - -fn user_display_name(username: &str, name: &str) -> String { - let name = name.trim(); - if name.is_empty() { - username.trim().to_string() - } else { - name.to_string() - } -} - -fn new_cdk() -> String { - Uuid::new_v4().simple().to_string().to_ascii_uppercase() -} - -fn normalize_cdk(cdk: &str) -> Result { - let cdk = cdk.trim().to_ascii_uppercase(); - if cdk.is_empty() { - return Err(AuthError::MissingCdk); - } - Ok(cdk) -} - -fn anonymous_cdk_user_id(cdk: &str) -> String { - format!("{ANONYMOUS_CDK_USER_PREFIX}{cdk}") -} - -fn anonymous_cdk_display_name(cdk: &str) -> String { - let suffix = cdk - .chars() - .filter(|ch| ch.is_ascii_alphanumeric()) - .rev() - .take(6) - .collect::>() - .into_iter() - .rev() - .collect::(); - if suffix.is_empty() { - "CDK 用户".to_string() - } else { - format!("CDK 用户 {suffix}") - } -} - -fn cookie_value(headers: &HeaderMap, name: &str) -> Option { - headers - .get(header::COOKIE)? - .to_str() - .ok()? - .split(';') - .filter_map(|part| part.trim().split_once('=')) - .find_map(|(key, value)| (key == name).then(|| value.to_string())) -} - -fn session_cookie(session: &str, secure: bool) -> HeaderValue { - HeaderValue::from_str(&format!( - "{SESSION_COOKIE_NAME}={session}; Path=/; HttpOnly; SameSite=Lax; Max-Age={SESSION_TTL_SECS}{}", - cookie_secure_suffix(secure) - )) - .expect("session cookie should be valid") -} - -fn oauth_state_cookie(state: &str, secure: bool) -> HeaderValue { - HeaderValue::from_str(&format!( - "{OAUTH_STATE_COOKIE_NAME}={state}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600{}", - cookie_secure_suffix(secure) - )) - .expect("oauth state cookie should be valid") -} - -fn clear_cookie(name: &str, secure: bool) -> HeaderValue { - HeaderValue::from_str(&format!( - "{name}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0{}", - cookie_secure_suffix(secure) - )) - .expect("clear cookie should be valid") -} - -fn cookie_secure_suffix(secure: bool) -> &'static str { - if secure { - "; Secure" - } else { - "" - } -} - -fn linuxdo_oauth_config(headers: &HeaderMap) -> Result { - let client_id = env::var(LINUXDO_CLIENT_ID_ENV).unwrap_or_default(); - let client_secret = env::var(LINUXDO_CLIENT_SECRET_ENV).unwrap_or_default(); - if client_id.trim().is_empty() || client_secret.trim().is_empty() { - return Err(AuthError::OAuthNotConfigured); - } - let redirect_uri = env::var(LINUXDO_REDIRECT_URI_ENV) - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) - .unwrap_or_else(|| request_base_url(headers) + "/api/oauth/linuxdo"); - let token_url = env::var("LINUX_DO_TOKEN_ENDPOINT") - .ok() - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| LINUXDO_TOKEN_URL.to_string()); - let user_url = env::var("LINUX_DO_USER_ENDPOINT") - .ok() - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| LINUXDO_USERINFO_URL.to_string()); - Ok(LinuxDoOAuthConfig { - client_id, - client_secret, - redirect_uri, - auth_url: LINUXDO_AUTH_URL.to_string(), - token_url, - user_url, - min_trust_level: configured_min_trust_level(), - }) -} - -fn configured_min_trust_level() -> i64 { - env::var("LINUXDO_MIN_TRUST_LEVEL") - .ok() - .and_then(|value| value.trim().parse::().ok()) - .unwrap_or(0) -} - -fn linuxdo_account_error( - active: bool, - silenced: bool, - trust_level: i64, - min_trust_level: i64, -) -> Option { - if !active { - return Some(AuthError::InactiveAccount); - } - if silenced { - return Some(AuthError::SilencedAccount); - } - if trust_level < min_trust_level { - return Some(AuthError::TrustLevel { - required: min_trust_level, - current: trust_level, - }); - } - None -} - -fn request_base_url(headers: &HeaderMap) -> String { - let scheme = request_scheme(headers); - let host = headers - .get(header::HOST) - .and_then(|value| value.to_str().ok()) - .filter(|value| !value.trim().is_empty()) - .unwrap_or("IP_REDACTED:8793"); - format!("{scheme}://{host}") -} - -fn request_scheme(headers: &HeaderMap) -> &'static str { - match headers - .get("x-forwarded-proto") - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.split(',').next()) - .map(str::trim) - { - Some("https") => "https", - Some("http") => "http", - _ => "http", - } -} - -fn request_is_https(headers: &HeaderMap) -> bool { - request_scheme(headers) == "https" -} - -fn auth_api_error(status: StatusCode, error: AuthError) -> (StatusCode, Json) { - ( - status, - Json(AuthApiResponse { - ok: false, - user: None, - error: Some(error.to_string()), - login_url: None, - }), - ) -} - -fn extract_auth_error( - status: StatusCode, - error: AuthError, -) -> (StatusCode, Json) { - ( - status, - Json(ExtractApiResponse { - ok: false, - output: None, - error: Some(error.to_string()), - job: None, - }), - ) -} - -async fn fetch_linuxdo_user( - config: &LinuxDoOAuthConfig, - code: &str, -) -> Result { - let client = reqwest::Client::builder() - .redirect(Policy::none()) - .timeout(Duration::from_secs(30)) - .build() - .map_err(|error| AuthError::OAuth(format!("HTTP 客户端创建失败:{error}")))?; - let token_response = client - .post(&config.token_url) - .basic_auth(&config.client_id, Some(&config.client_secret)) - .form(&[ - ("grant_type", "authorization_code"), - ("code", code), - ("redirect_uri", config.redirect_uri.as_str()), - ]) - .send() - .await - .map_err(|error| AuthError::OAuth(format!("换取 access token 失败:{error}")))?; - let token_status = token_response.status(); - let token_body = token_response - .text() - .await - .map_err(|error| AuthError::OAuth(format!("读取 token 响应失败:{error}")))?; - if !token_status.is_success() { - return Err(AuthError::OAuth(format!( - "换取 access token 失败:HTTP {token_status} {}", - token_body.chars().take(200).collect::() - ))); - } - let token = serde_json::from_str::(&token_body) - .map_err(|error| AuthError::OAuth(format!("解析 token 响应失败:{error}")))?; - if token.access_token.trim().is_empty() { - return Err(AuthError::OAuth( - "LinuxDo 没有返回 access token。".to_string(), - )); - } - - let user_response = client - .get(&config.user_url) - .bearer_auth(token.access_token) - .send() - .await - .map_err(|error| AuthError::OAuth(format!("读取 LinuxDo 用户失败:{error}")))?; - let user_status = user_response.status(); - let user_body = user_response - .text() - .await - .map_err(|error| AuthError::OAuth(format!("读取用户响应失败:{error}")))?; - if !user_status.is_success() { - return Err(AuthError::OAuth(format!( - "读取 LinuxDo 用户失败:HTTP {user_status} {}", - user_body.chars().take(200).collect::() - ))); - } - serde_json::from_str::(&user_body) - .map_err(|error| AuthError::OAuth(format!("解析 LinuxDo 用户失败:{error}"))) -} - -fn oauth_error_response(error: AuthError) -> Response { - let text = error.to_string(); - ( - StatusCode::BAD_REQUEST, - Html(format!( - "LinuxDo 登录失败

{}

返回首页

", - escape_html(&text) - )), - ) - .into_response() -} - -fn escape_html(text: &str) -> String { - text.replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) - .replace('\'', "'") -} - -#[derive(Clone)] -pub struct AppState { - queue: ExtractQueue, - auth: AuthStore, -} - -impl AppState { - pub async fn new() -> Self { - Self::with_queue_config_and_auth(configured_queue_config(), AuthStore::new_from_env().await) - } - - pub async fn with_queue_config(config: QueueConfig) -> Self { - Self::with_queue_config_and_auth(config, AuthStore::new_from_env().await) - } - - fn with_queue_config_and_auth(config: QueueConfig, auth: AuthStore) -> Self { - Self { - queue: ExtractQueue::new(config.normalized()), - auth, - } - } -} - -#[cfg(all(test, feature = "postgres-integration-tests"))] -impl AppState { - fn new_unstarted_for_test(capacity: usize) -> (Self, mpsc::Receiver) { - let auth = AuthStore::in_memory(); - let (queue, receiver) = ExtractQueue::new_unstarted_for_test(capacity, auth.clone()); - (Self { queue, auth }, receiver) - } -} - -#[derive(Clone)] -struct ExtractQueue { - sender: mpsc::Sender, - jobs: Arc>>, - cancel_flags: Arc>>>, - next_order: Arc, -} - -#[derive(Debug)] -struct ExtractJobMessage { - job_id: String, - input: ExtractInput, - cancel_flag: Arc, -} - -type ProgressSink = Arc; -const JOB_CANCELED_MESSAGE: &str = "任务已中断。"; - -#[derive(Debug, Clone)] -struct ExtractJob { - status: ExtractJobStatus, - order: u64, - steps: Vec, - output: Option, - error: Option, -} - -#[derive(Debug, thiserror::Error)] -enum QueueError { - #[error("队列已满,请稍后再试。")] - Full, - #[error("队列暂不可用,请重启服务。")] - Closed, -} - -impl ExtractQueue { - fn new(config: QueueConfig) -> Self { - let config = config.normalized(); - let finished_job_retained = config.finished_job_retained(); - let (sender, receiver) = mpsc::channel::(config.queue_capacity); - let receiver = Arc::new(TokioMutex::new(receiver)); - let jobs = Arc::new(StdMutex::new(BTreeMap::::new())); - let cancel_flags = Arc::new(StdMutex::new(BTreeMap::>::new())); - for _ in 0..config.worker_count { - let worker_jobs = Arc::clone(&jobs); - let worker_receiver = Arc::clone(&receiver); - let worker_cancel_flags = Arc::clone(&cancel_flags); - let _worker = tokio::spawn(async move { - loop { - let message = { - let mut receiver = worker_receiver.lock().await; - receiver.recv().await - }; - let Some(message) = message else { - break; - }; - if message.cancel_flag.load(Ordering::Relaxed) - || job_is_canceled(&worker_jobs, &message.job_id) - { - remove_cancel_flag(&worker_cancel_flags, &message.job_id); - prune_finished_jobs(&worker_jobs, finished_job_retained); - continue; - } - if !set_job_running(&worker_jobs, &message.job_id) { - remove_cancel_flag(&worker_cancel_flags, &message.job_id); - prune_finished_jobs(&worker_jobs, finished_job_retained); - continue; - } - let progress_jobs = Arc::clone(&worker_jobs); - let progress_job_id = message.job_id.clone(); - let progress_cancel_flag = Arc::clone(&message.cancel_flag); - let progress: ProgressSink = Arc::new(move |step| { - if !progress_cancel_flag.load(Ordering::Relaxed) { - push_job_step(&progress_jobs, &progress_job_id, step); - } - }); - let result = - run_extract_job(message.input, Some(progress), message.cancel_flag).await; - set_job_finished(&worker_jobs, &message.job_id, result); - remove_cancel_flag(&worker_cancel_flags, &message.job_id); - prune_finished_jobs(&worker_jobs, finished_job_retained); - } - }); - } - - Self { - sender, - jobs, - cancel_flags, - next_order: Arc::new(AtomicU64::new(1)), - } - } - - async fn enqueue(&self, input: ExtractInput) -> Result { - let job_id = Uuid::new_v4().to_string(); - let order = self.next_order.fetch_add(1, Ordering::Relaxed); - let cancel_flag = Arc::new(AtomicBool::new(false)); - { - let mut jobs = self.jobs.lock().expect("queue mutex poisoned"); - jobs.insert( - job_id.clone(), - ExtractJob { - status: ExtractJobStatus::Queued, - order, - steps: vec![Step { - name: "queued".to_string(), - status: "queued".to_string(), - detail: "任务已进入队列,等待开始。".to_string(), - }], - output: None, - error: None, - }, - ); - } - { - let mut flags = self.cancel_flags.lock().expect("cancel mutex poisoned"); - flags.insert(job_id.clone(), Arc::clone(&cancel_flag)); - } - - let message = ExtractJobMessage { - job_id: job_id.clone(), - input, - cancel_flag, - }; - match self.sender.try_send(message) { - Ok(()) => self.snapshot(&job_id).ok_or(QueueError::Closed), - Err(mpsc::error::TrySendError::Full(message)) => { - self.remove(&message.job_id); - Err(QueueError::Full) - } - Err(mpsc::error::TrySendError::Closed(message)) => { - self.remove(&message.job_id); - Err(QueueError::Closed) - } - } - } - - fn snapshot(&self, job_id: &str) -> Option { - snapshot_from_jobs(&self.jobs, job_id) - } - - async fn cancel(&self, job_id: &str) -> Option { - let mut should_signal_cancel = false; - { - let mut jobs = self.jobs.lock().expect("queue mutex poisoned"); - let job = jobs.get_mut(job_id)?; - if matches!( - job.status, - ExtractJobStatus::Queued | ExtractJobStatus::Running - ) { - should_signal_cancel = true; - job.status = ExtractJobStatus::Canceled; - job.output = None; - job.error = Some(JOB_CANCELED_MESSAGE.to_string()); - job.steps.push(Step { - name: "canceled".to_string(), - status: "warn".to_string(), - detail: JOB_CANCELED_MESSAGE.to_string(), - }); - } - } - if should_signal_cancel { - let flags = self.cancel_flags.lock().expect("cancel mutex poisoned"); - if let Some(flag) = flags.get(job_id) { - flag.store(true, Ordering::Relaxed); - } - } - self.snapshot(job_id) - } - - fn remove(&self, job_id: &str) { - let mut jobs = self.jobs.lock().expect("queue mutex poisoned"); - jobs.remove(job_id); - drop(jobs); - remove_cancel_flag(&self.cancel_flags, job_id); - } - - #[cfg(all(test, feature = "postgres-integration-tests"))] - fn new_unstarted_for_test( - capacity: usize, - _auth: AuthStore, - ) -> (Self, mpsc::Receiver) { - let (sender, receiver) = mpsc::channel::(capacity); - ( - Self { - sender, - jobs: Arc::new(StdMutex::new(BTreeMap::::new())), - cancel_flags: Arc::new(StdMutex::new(BTreeMap::>::new())), - next_order: Arc::new(AtomicU64::new(1)), - }, - receiver, - ) - } -} - -async fn run_extract_job( - input: ExtractInput, - progress: Option, - cancel_flag: Arc, -) -> Result { - let transport = ReqwestTransport::new(&input.proxy)?; - let mut transport = CancellableTransport { - inner: transport, - cancel_flag, - }; - extract_link_with_progress(&mut transport, input, progress).await -} - -struct CancellableTransport { - inner: T, - cancel_flag: Arc, -} - -#[async_trait] -impl Transport for CancellableTransport { - async fn send(&mut self, request: HttpRequest) -> Result { - if self.cancel_flag.load(Ordering::Relaxed) { - return Err(ExtractError::Canceled); - } - let response = self.inner.send(request).await; - if self.cancel_flag.load(Ordering::Relaxed) { - return Err(ExtractError::Canceled); - } - response - } -} - -fn set_job_running(jobs: &Arc>>, job_id: &str) -> bool { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - if let Some(job) = jobs.get_mut(job_id) { - if job.status != ExtractJobStatus::Queued { - return false; - } - job.status = ExtractJobStatus::Running; - job.steps.push(Step { - name: "running".to_string(), - status: "running".to_string(), - detail: "任务已开始执行。".to_string(), - }); - return true; - } - false -} - -fn push_job_step(jobs: &Arc>>, job_id: &str, step: Step) { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - if let Some(job) = jobs.get_mut(job_id) { - if job.status == ExtractJobStatus::Canceled { - return; - } - job.steps.push(step); - } -} - -fn set_job_finished( - jobs: &Arc>>, - job_id: &str, - result: Result, -) { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - if let Some(job) = jobs.get_mut(job_id) { - if job.status == ExtractJobStatus::Canceled { - return; - } - match result { - Ok(output) => { - job.status = ExtractJobStatus::Completed; - if job.steps.is_empty() { - job.steps = output.steps.clone(); - } else { - for step in &output.steps { - if !job.steps.iter().any(|existing| existing == step) { - job.steps.push(step.clone()); - } - } - } - job.output = Some(output); - job.error = None; - } - Err(error) => { - job.status = ExtractJobStatus::Failed; - job.output = None; - let error = error.to_string(); - job.steps.push(Step { - name: "error".to_string(), - status: "error".to_string(), - detail: error.clone(), - }); - job.error = Some(error); - } - } - } -} - -fn job_is_canceled(jobs: &Arc>>, job_id: &str) -> bool { - let jobs = jobs.lock().expect("queue mutex poisoned"); - jobs.get(job_id) - .map(|job| job.status == ExtractJobStatus::Canceled) - .unwrap_or(true) -} - -fn remove_cancel_flag( - cancel_flags: &Arc>>>, - job_id: &str, -) { - let mut flags = cancel_flags.lock().expect("cancel mutex poisoned"); - flags.remove(job_id); -} - -fn snapshot_from_jobs( - jobs: &Arc>>, - job_id: &str, -) -> Option { - let jobs = jobs.lock().expect("queue mutex poisoned"); - let job = jobs.get(job_id)?.clone(); - snapshot_from_locked_jobs(&jobs, job_id, job) -} - -fn snapshot_from_locked_jobs( - jobs: &BTreeMap, - job_id: &str, - job: ExtractJob, -) -> Option { - let queue_size = jobs - .values() - .filter(|job| job.status == ExtractJobStatus::Queued) - .count(); - let position = match job.status { - ExtractJobStatus::Queued => jobs - .values() - .filter(|candidate| { - candidate.status == ExtractJobStatus::Queued && candidate.order <= job.order - }) - .count(), - _ => 0, - }; - Some(ExtractJobSnapshot { - job_id: job_id.to_string(), - status: job.status, - position, - queue_size, - steps: job.steps, - output: job.output, - error: job.error, - }) -} - -fn prune_finished_jobs( - jobs: &Arc>>, - finished_job_retained: usize, -) { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - let mut finished = jobs - .iter() - .filter(|(_, job)| { - matches!( - job.status, - ExtractJobStatus::Completed | ExtractJobStatus::Failed | ExtractJobStatus::Canceled - ) - }) - .map(|(job_id, job)| (job.order, job_id.clone())) - .collect::>(); - if finished.len() <= finished_job_retained { - return; - } - finished.sort_by_key(|(order, _)| *order); - let remove_count = finished.len() - finished_job_retained; - for (_, job_id) in finished.into_iter().take(remove_count) { - jobs.remove(&job_id); - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HttpRequest { - pub method: String, - pub url: String, - pub headers: BTreeMap, - pub body: RequestBody, - pub stage_proxy: String, - pub proxy_url: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum RequestBody { - Empty, - Json(Value), - Form(BTreeMap), -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HttpResponse { - pub status: u16, - pub headers: BTreeMap, - pub body: String, -} - -#[derive(Debug, thiserror::Error)] -pub enum ExtractError { - #[error("Access Token is required")] - MissingToken, - #[error("iDEAL Checkout 主代理池不能为空。")] - MissingCheckoutProxyPool, - #[error("iDEAL Promotion Update 代理池不能为空。")] - MissingPromotionProxyPool, - #[error("iDEAL Checkout 主代理池第 {0} 行格式无效。")] - InvalidCheckoutProxy(usize), - #[error("iDEAL Promotion Update 代理池第 {0} 行格式无效。")] - InvalidPromotionProxy(usize), - #[error("PayPal US Checkout / Approve 代理池不能为空。")] - MissingPaypalCheckoutProxyPool, - #[error("PayPal VN Promotion Update 代理池不能为空。")] - MissingPaypalPromotionProxyPool, - #[error("PayPal TR Provider 代理池不能为空。")] - MissingPaypalProviderProxyPool, - #[error("PayPal US Checkout / Approve 代理池第 {0} 行格式无效。")] - InvalidPaypalCheckoutProxy(usize), - #[error("PayPal VN Promotion Update 代理池第 {0} 行格式无效。")] - InvalidPaypalPromotionProxy(usize), - #[error("PayPal TR Provider 代理池第 {0} 行格式无效。")] - InvalidPaypalProviderProxy(usize), - #[error("任务已中断。")] - Canceled, - #[error("non-default --base-url must be localhost or loopback: {0}")] - UnsafeBaseUrl(String), - #[error("http error: {0}")] - Http(String), - #[error("bad response: {0}")] - BadResponse(String), - #[error("paypal provider failed: {detail}")] - PaypalProviderFailed { - detail: String, - cs_id: String, - processor_entity: String, - stripe_hosted_url: String, - amount: String, - payment_method_id: String, - }, -} - -#[async_trait] -pub trait Transport { - async fn send(&mut self, request: HttpRequest) -> Result; -} - -pub struct ReqwestTransport; - -impl ReqwestTransport { - pub fn new(_proxy: &str) -> Result { - Ok(Self) - } -} - -pub async fn app_router() -> Router { - app_router_with_state(AppState::new().await) -} - -pub fn app_router_with_state(state: AppState) -> Router { - Router::new() - .route("/", get(index_page)) - .route("/api/config", get(api_config)) - .route("/api/auth/me", get(api_auth_me)) - .route("/api/auth/logout", post(api_auth_logout)) - .route("/api/cdk/bind", post(api_bind_cdk)) - .route("/api/oauth/linuxdo/login", get(linuxdo_oauth_login)) - .route("/api/oauth/linuxdo", get(linuxdo_oauth_callback)) - .route("/api/extract", post(api_extract)) - .route("/api/extract/{job_id}/cancel", post(api_extract_cancel)) - .route("/api/extract/{job_id}", get(api_extract_status)) - .with_state(state) -} - -pub fn frontend_html() -> &'static str { - include_str!("index.html") -} - -async fn index_page() -> Html<&'static str> { - Html(frontend_html()) -} - -pub async fn api_config() -> Json { - Json(locked_config()) -} - -pub async fn api_auth_me( - State(state): State, - headers: HeaderMap, -) -> (StatusCode, Json) { - match state.auth.user_from_headers(&headers).await { - Ok(user) => ( - StatusCode::OK, - Json(AuthApiResponse { - ok: true, - user: Some(user), - error: None, - login_url: None, - }), - ), - Err(error) => auth_api_error(StatusCode::OK, error), - } -} - -pub async fn api_auth_logout(State(state): State, headers: HeaderMap) -> Response { - let secure_cookie = request_is_https(&headers); - if let Some(session) = cookie_value(&headers, SESSION_COOKIE_NAME) { - let _ = state.auth.logout(&session).await; - } - let mut response = Json(AuthApiResponse { - ok: true, - user: None, - error: None, - login_url: None, - }) - .into_response(); - response.headers_mut().append( - header::SET_COOKIE, - clear_cookie(SESSION_COOKIE_NAME, secure_cookie), - ); - response -} - -pub async fn api_bind_cdk( - State(state): State, - headers: HeaderMap, - Json(input): Json, -) -> Response { - let secure_cookie = request_is_https(&headers); - let logged_in_user = match state.auth.user_from_headers(&headers).await { - Ok(user) => Some(user), - Err(AuthError::Unauthorized) => None, - Err(error) => return auth_api_error(StatusCode::UNAUTHORIZED, error).into_response(), - }; - - if let Some(user) = logged_in_user { - match state.auth.bind_cdk(&user.linuxdo_id, &input.cdk).await { - Ok(user) => { - return ( - StatusCode::OK, - Json(AuthApiResponse { - ok: true, - user: Some(user), - error: None, - login_url: None, - }), - ) - .into_response(); - } - Err(AuthError::MissingCdk) => { - return auth_api_error(StatusCode::BAD_REQUEST, AuthError::MissingCdk) - .into_response() - } - Err(AuthError::CdkNotReady) => { - return auth_api_error(StatusCode::CONFLICT, AuthError::CdkNotReady).into_response() - } - Err(AuthError::CdkUnavailable) => { - return auth_api_error(StatusCode::NOT_FOUND, AuthError::CdkUnavailable) - .into_response() - } - Err(AuthError::NoQuota) => { - return auth_api_error(StatusCode::FORBIDDEN, AuthError::NoQuota).into_response() - } - Err(error) => return auth_api_error(StatusCode::UNAUTHORIZED, error).into_response(), - } - } - - let (session, user) = match state.auth.login_cdk_user(&input.cdk).await { - Ok((session, user)) => (session, user), - Err(AuthError::MissingCdk) => { - return auth_api_error(StatusCode::BAD_REQUEST, AuthError::MissingCdk).into_response() - } - Err(AuthError::NoQuota) => { - return auth_api_error(StatusCode::FORBIDDEN, AuthError::NoQuota).into_response() - } - Err(AuthError::CdkUnavailable) => { - return auth_api_error(StatusCode::NOT_FOUND, AuthError::CdkUnavailable).into_response() - } - Err(error) => return auth_api_error(StatusCode::UNAUTHORIZED, error).into_response(), - }; - - let mut response = ( - StatusCode::OK, - Json(AuthApiResponse { - ok: true, - user: Some(user), - error: None, - login_url: None, - }), - ) - .into_response(); - response - .headers_mut() - .append(header::SET_COOKIE, session_cookie(&session, secure_cookie)); - response -} - -pub async fn linuxdo_oauth_login(State(state): State, headers: HeaderMap) -> Response { - let secure_cookie = request_is_https(&headers); - let config = match linuxdo_oauth_config(&headers) { - Ok(config) => config, - Err(error) => return oauth_error_response(error), - }; - let state_value = match state.auth.create_oauth_state().await { - Ok(state_value) => state_value, - Err(error) => return oauth_error_response(error), - }; - let mut auth_url = match Url::parse(&config.auth_url) { - Ok(url) => url, - Err(_) => return oauth_error_response(AuthError::OAuth("授权地址无效。".to_string())), - }; - auth_url - .query_pairs_mut() - .append_pair("response_type", "code") - .append_pair("client_id", &config.client_id) - .append_pair("redirect_uri", &config.redirect_uri) - .append_pair("state", &state_value); - let mut response = Redirect::temporary(auth_url.as_str()).into_response(); - response.headers_mut().append( - header::SET_COOKIE, - oauth_state_cookie(&state_value, secure_cookie), - ); - response -} - -pub async fn linuxdo_oauth_callback( - State(state): State, - headers: HeaderMap, - Query(query): Query, -) -> Response { - let secure_cookie = request_is_https(&headers); - if let Some(error) = query.error { - return oauth_error_response(AuthError::OAuth(error)); - } - let Some(code) = query.code.filter(|value| !value.trim().is_empty()) else { - return oauth_error_response(AuthError::OAuth("缺少授权码。".to_string())); - }; - let Some(returned_state) = query.state.filter(|value| !value.trim().is_empty()) else { - return oauth_error_response(AuthError::OAuth("缺少 state。".to_string())); - }; - let Some(cookie_state) = cookie_value(&headers, OAUTH_STATE_COOKIE_NAME) else { - return oauth_error_response(AuthError::OAuth("授权状态已过期,请重新登录。".to_string())); - }; - let state_valid = match state.auth.consume_oauth_state(&returned_state).await { - Ok(state_valid) => state_valid, - Err(error) => return oauth_error_response(error), - }; - if cookie_state != returned_state || !state_valid { - return oauth_error_response(AuthError::OAuth( - "授权状态校验失败,请重新登录。".to_string(), - )); - } - let config = match linuxdo_oauth_config(&headers) { - Ok(config) => config, - Err(error) => return oauth_error_response(error), - }; - let linuxdo_user = match fetch_linuxdo_user(&config, &code).await { - Ok(user) => user, - Err(error) => return oauth_error_response(error), - }; - let (session, _) = match state - .auth - .login_linuxdo_user(linuxdo_user, config.min_trust_level) - .await - { - Ok(value) => value, - Err(error) => return oauth_error_response(error), - }; - let mut response = Redirect::to("/").into_response(); - response - .headers_mut() - .append(header::SET_COOKIE, session_cookie(&session, secure_cookie)); - response.headers_mut().append( - header::SET_COOKIE, - clear_cookie(OAUTH_STATE_COOKIE_NAME, secure_cookie), - ); - response -} - -pub async fn api_extract( - State(state): State, - _headers: HeaderMap, - Json(input): Json, -) -> (StatusCode, Json) { - if normalize_access_token(&input.access_token).is_none() { - return api_error(StatusCode::BAD_REQUEST, ExtractError::MissingToken); - } - let input = match extract_input_for_api(input) { - Ok(input) => input, - Err(error) => return api_error(StatusCode::BAD_REQUEST, error), - }; - match state.queue.enqueue(input).await { - Ok(job) => ( - StatusCode::ACCEPTED, - Json(ExtractApiResponse { - ok: true, - output: None, - error: None, - job: Some(job), - }), - ), - Err(QueueError::Full) => api_queue_error(StatusCode::TOO_MANY_REQUESTS, QueueError::Full), - Err(QueueError::Closed) => { - api_queue_error(StatusCode::SERVICE_UNAVAILABLE, QueueError::Closed) - } - } -} - -pub async fn api_extract_cancel( - State(state): State, - _headers: HeaderMap, - Path(job_id): Path, -) -> (StatusCode, Json) { - match state.queue.cancel(&job_id).await { - Some(job) => ( - StatusCode::OK, - Json(ExtractApiResponse { - ok: true, - output: job.output.clone(), - error: job.error.clone(), - job: Some(job), - }), - ), - None => ( - StatusCode::NOT_FOUND, - Json(ExtractApiResponse { - ok: false, - output: None, - error: Some("任务不存在或已过期。".to_string()), - job: None, - }), - ), - } -} - -pub async fn api_extract_status( - State(state): State, - _headers: HeaderMap, - Path(job_id): Path, -) -> (StatusCode, Json) { - match state.queue.snapshot(&job_id) { - Some(job) => { - let ok = !matches!( - job.status, - ExtractJobStatus::Failed | ExtractJobStatus::Canceled - ); - let output = job.output.clone(); - let error = job.error.clone(); - ( - StatusCode::OK, - Json(ExtractApiResponse { - ok, - output, - error, - job: Some(job), - }), - ) - } - None => ( - StatusCode::NOT_FOUND, - Json(ExtractApiResponse { - ok: false, - output: None, - error: Some("任务不存在或已过期。".to_string()), - job: None, - }), - ), - } -} - -fn api_error(status: StatusCode, error: ExtractError) -> (StatusCode, Json) { - ( - status, - Json(ExtractApiResponse { - ok: false, - output: None, - error: Some(error.to_string()), - job: None, - }), - ) -} - -fn api_queue_error( - status: StatusCode, - error: QueueError, -) -> (StatusCode, Json) { - ( - status, - Json(ExtractApiResponse { - ok: false, - output: None, - error: Some(error.to_string()), - job: None, - }), - ) -} - -fn extract_input_for_api(input: ExtractApiInput) -> Result { - let link_type = input - .link_type - .as_deref() - .unwrap_or("ideal") - .trim() - .to_ascii_lowercase(); - match link_type.as_str() { - "" | "ideal" => { - let checkout_proxy_pool = - parse_proxy_pool(&input.checkout_proxy_pool, ProxyPoolKind::Checkout)?; - if checkout_proxy_pool.is_empty() { - return Err(ExtractError::MissingCheckoutProxyPool); - } - let promotion_proxy_pool = - parse_proxy_pool(&input.promotion_proxy_pool, ProxyPoolKind::Promotion)?; - if promotion_proxy_pool.is_empty() { - return Err(ExtractError::MissingPromotionProxyPool); - } - Ok(ExtractInput { - access_token: input.access_token, - proxy: checkout_proxy_pool[0].clone(), - checkout_proxy_pool, - promotion_proxy_pool, - paypal_provider_proxy_pool: Vec::new(), - base_url: String::new(), - link_type: "ideal".to_string(), - }) - } - "paypal" => { - let paypal_checkout_proxy_pool = parse_proxy_pool( - &input.paypal_checkout_proxy_pool, - ProxyPoolKind::PaypalCheckout, - )?; - if paypal_checkout_proxy_pool.is_empty() { - return Err(ExtractError::MissingPaypalCheckoutProxyPool); - } - let paypal_promotion_proxy_pool = parse_proxy_pool( - &input.paypal_promotion_proxy_pool, - ProxyPoolKind::PaypalPromotion, - )?; - if paypal_promotion_proxy_pool.is_empty() { - return Err(ExtractError::MissingPaypalPromotionProxyPool); - } - let paypal_provider_proxy_pool = parse_proxy_pool( - &input.paypal_provider_proxy_pool, - ProxyPoolKind::PaypalProvider, - )?; - if paypal_provider_proxy_pool.is_empty() { - return Err(ExtractError::MissingPaypalProviderProxyPool); - } - Ok(ExtractInput { - access_token: input.access_token, - proxy: paypal_checkout_proxy_pool[0].clone(), - checkout_proxy_pool: paypal_checkout_proxy_pool, - promotion_proxy_pool: paypal_promotion_proxy_pool, - paypal_provider_proxy_pool, - base_url: String::new(), - link_type: "paypal".to_string(), - }) - } - other => Err(ExtractError::BadResponse(format!( - "unsupported link_type: {other}" - ))), - } -} - -#[derive(Clone, Copy)] -enum ProxyPoolKind { - Checkout, - Promotion, - PaypalCheckout, - PaypalPromotion, - PaypalProvider, -} - -fn parse_proxy_pool(text: &str, kind: ProxyPoolKind) -> Result, ExtractError> { - let mut proxies = Vec::new(); - for (line_index, line) in text.lines().enumerate() { - let proxy = normalize_proxy_url_for_reqwest(line.trim()); - if proxy.is_empty() || proxies.contains(&proxy) { - continue; - } - if reqwest::Proxy::all(&proxy).is_err() { - return Err(match kind { - ProxyPoolKind::Checkout => ExtractError::InvalidCheckoutProxy(line_index + 1), - ProxyPoolKind::Promotion => ExtractError::InvalidPromotionProxy(line_index + 1), - ProxyPoolKind::PaypalCheckout => { - ExtractError::InvalidPaypalCheckoutProxy(line_index + 1) - } - ProxyPoolKind::PaypalPromotion => { - ExtractError::InvalidPaypalPromotionProxy(line_index + 1) - } - ProxyPoolKind::PaypalProvider => { - ExtractError::InvalidPaypalProviderProxy(line_index + 1) - } - }); - } - proxies.push(proxy); - } - Ok(proxies) -} - -fn configured_default_proxy() -> String { - let env_proxy = env::var(DEFAULT_PROXY_ENV) - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()); - env_proxy - .or_else(|| { - fs::read_to_string(".env") - .ok() - .map(|text| default_proxy_from_env_text(&text)) - .filter(|value| !value.is_empty()) - }) - .unwrap_or_default() -} - -fn default_proxy_from_env_text(text: &str) -> String { - env_value_from_text(text, DEFAULT_PROXY_ENV).unwrap_or_default() -} - -fn env_value_from_text(text: &str, wanted_key: &str) -> Option { - for line in text.lines() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - let line = line.strip_prefix("export ").unwrap_or(line).trim(); - let Some((key, value)) = line.split_once('=') else { - continue; - }; - if key.trim() != wanted_key { - continue; - } - let value = value.trim(); - return Some( - value - .strip_prefix('"') - .and_then(|value| value.strip_suffix('"')) - .or_else(|| { - value - .strip_prefix('\'') - .and_then(|value| value.strip_suffix('\'')) - }) - .unwrap_or(value) - .trim() - .to_string(), - ); - } - None -} - -#[async_trait] -impl Transport for ReqwestTransport { - async fn send(&mut self, request: HttpRequest) -> Result { - let mut builder = reqwest::Client::builder() - .redirect(Policy::none()) - .timeout(Duration::from_secs(30)); - if !request.proxy_url.trim().is_empty() { - let proxy_url = normalize_proxy_url_for_reqwest(&request.proxy_url); - let proxy = reqwest::Proxy::all(&proxy_url) - .map_err(|error| ExtractError::Http(format!("invalid proxy: {error}")))?; - builder = builder.proxy(proxy); - } - let client = builder - .build() - .map_err(|error| ExtractError::Http(format!("client build failed: {error}")))?; - let method = reqwest::Method::from_bytes(request.method.as_bytes()) - .map_err(|error| ExtractError::Http(format!("invalid method: {error}")))?; - let mut req = client.request(method.clone(), &request.url); - for (key, value) in &request.headers { - req = req.header(key, value); - } - match &request.body { - RequestBody::Empty => {} - RequestBody::Json(body) => req = req.json(body), - RequestBody::Form(form) if method == reqwest::Method::GET => req = req.query(form), - RequestBody::Form(form) => req = req.form(form), - } - let response = req - .send() - .await - .map_err(|error| ExtractError::Http(format!("request failed: {error}")))?; - let status = response.status().as_u16(); - let mut headers = BTreeMap::new(); - for (key, value) in response.headers() { - if let Ok(text) = value.to_str() { - headers.insert(key.as_str().to_ascii_lowercase(), text.to_string()); - } - } - let body = response - .text() - .await - .map_err(|error| ExtractError::Http(format!("response body failed: {error}")))?; - Ok(HttpResponse { - status, - headers, - body, - }) - } -} - -pub const fn locked_config() -> LockedConfig { - config_for_link_type(LinkType::Ideal) -} - -const fn config_for_link_type(link_type: LinkType) -> LockedConfig { - match link_type { - LinkType::Ideal => ideal_config(), - LinkType::Paypal => paypal_config(), - } -} - -const fn ideal_config() -> LockedConfig { - LockedConfig { - link_type: "ideal", - billing_country: "NL", - currency: "EUR", - checkout_ui_mode: "custom", - payment_locale: "auto", - client_fingerprint: "apple-safari", - user_agent: APPLE_SAFARI_USER_AGENT, - checkout_proxy_region: CHECKOUT_REGION, - promotion_proxy_region: Some(PROMOTION_REGION), - provider_proxy_region: PROVIDER_REGION, - approve_proxy_region: APPROVE_REGION, - approve_max_attempts: MAX_APPROVE_ATTEMPTS, - approve_concurrency: APPROVE_CONCURRENCY, - } -} - -const fn paypal_config() -> LockedConfig { - LockedConfig { - link_type: "paypal", - billing_country: PAYPAL_BILLING_COUNTRY, - currency: "USD", - checkout_ui_mode: "hosted", - payment_locale: "auto", - client_fingerprint: "chrome", - user_agent: PAYPAL_USER_AGENT, - checkout_proxy_region: PAYPAL_CHECKOUT_REGION, - promotion_proxy_region: Some(PAYPAL_PROMOTION_REGION), - provider_proxy_region: PAYPAL_PROVIDER_REGION, - approve_proxy_region: PAYPAL_APPROVE_REGION, - approve_max_attempts: PAYPAL_APPROVE_MAX_ATTEMPTS, - approve_concurrency: APPROVE_CONCURRENCY, - } -} - -pub fn proxy_for_region(proxy: &str, region: &str) -> String { - let proxy = proxy.trim(); - let region = proxy_region_value(proxy, region); - if proxy.is_empty() || region.is_empty() { - return proxy.to_string(); - } - static REGION_RE: OnceLock = OnceLock::new(); - static ST_RE: OnceLock = OnceLock::new(); - let region_re = - REGION_RE.get_or_init(|| Regex::new(r"region-[A-Za-z]{2}").expect("valid region regex")); - let st_re = ST_RE.get_or_init(|| Regex::new(r"-st-[^-:@]+-sid-").expect("valid sticky regex")); - let rewritten = region_re - .replace(proxy, format!("region-{region}")) - .to_string(); - if region.eq_ignore_ascii_case("JP") { - rewritten - } else { - st_re.replace(&rewritten, "-sid-").to_string() - } -} - -fn proxy_with_fresh_sid(proxy: &str) -> String { - let proxy = proxy.trim(); - if proxy.is_empty() { - return String::new(); - } - static SID_RE: OnceLock = OnceLock::new(); - let sid_re = SID_RE.get_or_init(|| Regex::new(r"sid-[^-:@]*-t-").expect("valid sid regex")); - if sid_re.is_match(proxy) { - return sid_re - .replace( - proxy, - format!("sid-{}-t-", &Uuid::new_v4().simple().to_string()[..8]), - ) - .to_string(); - } - proxy.to_string() -} - -fn proxy_region_value(proxy: &str, region: &str) -> String { - let region = region.trim(); - if uses_lowercase_proxy_region(proxy) { - region.to_ascii_lowercase() - } else { - region.to_ascii_uppercase() - } -} - -fn uses_lowercase_proxy_region(proxy: &str) -> bool { - let proxy = proxy.trim().to_ascii_lowercase(); - proxy.contains("PROXY_REDACTED") || (!proxy.contains("://") && proxy.split(':').count() >= 4) -} - -fn normalize_proxy_url_for_reqwest(proxy: &str) -> String { - let proxy = proxy.trim(); - if proxy.is_empty() || proxy.contains("://") { - return proxy.to_string(); - } - let mut parts = proxy.splitn(4, ':'); - let Some(host) = parts.next() else { - return proxy.to_string(); - }; - let Some(port) = parts.next() else { - return format!("http://{proxy}"); - }; - let Some(username) = parts.next() else { - return format!("http://{proxy}"); - }; - let Some(password) = parts.next() else { - return format!("http://{proxy}"); - }; - if host.trim().is_empty() || port.parse::().is_err() { - return format!("http://{proxy}"); - } - let Ok(mut url) = Url::parse(&format!("http://{host}:{port}")) else { - return format!("http://{proxy}"); - }; - let _ = url.set_username(username); - let _ = url.set_password(Some(password)); - url.to_string() -} - -fn proxy_seed_for_attempt(proxy: &str, attempt: usize) -> String { - if attempt <= 1 { - proxy.to_string() - } else { - proxy_with_fresh_sid(proxy) - } -} - -fn proxy_region_from_url(proxy: &str) -> String { - static REGION_RE: OnceLock = OnceLock::new(); - let region_re = - REGION_RE.get_or_init(|| Regex::new(r"region-([A-Za-z]{2})").expect("valid region regex")); - region_re - .captures(proxy) - .and_then(|captures| captures.get(1)) - .map(|region| region.as_str().to_ascii_uppercase()) - .unwrap_or_default() -} - -fn proxy_summary(proxy: &str) -> String { - let proxy = proxy.trim(); - if proxy.is_empty() { - return "no proxy".to_string(); - } - let region = proxy_region_from_url(proxy); - let target = normalize_proxy_url_for_reqwest(proxy); - let host = Url::parse(&target) - .ok() - .and_then(|url| url.host_str().map(ToOwned::to_owned)) - .unwrap_or_else(|| "***".to_string()); - if region.is_empty() { - host - } else { - format!("{region} / {host}") - } -} - -fn approved_proxy_cache_lock() -> &'static StdMutex<()> { - static LOCK: OnceLock> = OnceLock::new(); - LOCK.get_or_init(|| StdMutex::new(())) -} - -fn approved_proxy_cache_key(token: &str, link_type: LinkType, region: &str) -> String { - format!( - "{}|{}|{}", - approved_proxy_account_key(token), - link_type.as_str(), - region.trim().to_ascii_uppercase() - ) -} - -fn approved_proxy_account_key(token: &str) -> String { - let Some(payload) = jwt_payload(token) else { - return "anonymous".to_string(); - }; - let profile = payload - .get("https://api.openai.com/profile") - .and_then(Value::as_object); - for value in [ - profile - .and_then(|profile| { - profile - .get("email") - .or_else(|| profile.get("email_address")) - }) - .and_then(Value::as_str), - payload.get("chatgpt_account_id").and_then(Value::as_str), - payload.get("chatgpt_user_id").and_then(Value::as_str), - payload.get("user_id").and_then(Value::as_str), - payload.get("sub").and_then(Value::as_str), - ] - .into_iter() - .flatten() - { - let text = value.trim().to_ascii_lowercase(); - if !text.is_empty() { - return stable_hash_24(&text); - } - } - "anonymous".to_string() -} - -fn stable_hash_24(value: &str) -> String { - fn fnv(seed: u64, value: &str) -> u64 { - let mut hash = seed; - for byte in value.as_bytes() { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(0x100000001b3); - } - hash - } - let first = fnv(0xcbf29ce484222325, value); - let second = fnv(0x84222325cbf29ce4, value); - format!("{:016x}{:08x}", first, second as u32) -} - -fn read_approved_proxy_cache() -> BTreeMap { - fs::read_to_string(APPROVED_PROXY_CACHE_FILE) - .ok() - .and_then(|text| serde_json::from_str::>(&text).ok()) - .unwrap_or_default() -} - -fn write_approved_proxy_cache(cache: &BTreeMap) { - let path = FsPath::new(APPROVED_PROXY_CACHE_FILE); - if let Some(parent) = path.parent() { - let _ = fs::create_dir_all(parent); - } else { - let _ = fs::create_dir_all(RUN_OUTPUT_DIR); - } - if let Ok(text) = serde_json::to_string_pretty(cache) { - let _ = fs::write(path, format!("{text}\n")); - } -} - -fn approved_proxy_for_request(token: &str, link_type: LinkType, region: &str) -> Option { - let region = region.trim().to_ascii_uppercase(); - let _guard = approved_proxy_cache_lock() - .lock() - .expect("approved proxy cache mutex poisoned"); - let cache = read_approved_proxy_cache(); - let entry = cache.get(&approved_proxy_cache_key(token, link_type, ®ion))?; - if entry.proxy.trim().is_empty() { - return None; - } - let entry_region = entry.region.trim().to_ascii_uppercase(); - if !region.is_empty() && !entry_region.is_empty() && entry_region != region { - return None; - } - Some(entry.proxy.clone()) -} - -fn remember_approved_proxy(token: &str, link_type: LinkType, region: &str, proxy: &str) { - let proxy = proxy.trim(); - if proxy.is_empty() { - return; - } - let region = region.trim().to_ascii_uppercase(); - let account_key = approved_proxy_account_key(token); - let key = approved_proxy_cache_key(token, link_type, ®ion); - let entry = ApprovedProxyEntry { - proxy: proxy.to_string(), - region, - link_type: link_type.as_str().to_string(), - account_key, - saved_at: now_epoch_secs().to_string(), - proxy_summary: proxy_summary(proxy), - }; - let _guard = approved_proxy_cache_lock() - .lock() - .expect("approved proxy cache mutex poisoned"); - let mut cache = read_approved_proxy_cache(); - cache.insert(key, entry); - write_approved_proxy_cache(&cache); -} - -async fn extract_link_with_progress( - transport: &mut T, - input: ExtractInput, - progress: Option, -) -> Result { - match LinkType::parse(&input.link_type)? { - LinkType::Ideal => extract_ideal_link_with_progress(transport, input, progress).await, - LinkType::Paypal => extract_paypal_link_with_progress(transport, input, progress).await, - } -} - -pub async fn extract_ideal_link( - transport: &mut T, - input: ExtractInput, -) -> Result { - extract_ideal_link_with_progress(transport, input, None).await -} - -async fn extract_ideal_link_with_progress( - transport: &mut T, - input: ExtractInput, - progress: Option, -) -> Result { - let progress = progress.as_ref(); - let token = normalize_access_token(&input.access_token).ok_or(ExtractError::MissingToken)?; - let base = EndpointBase::new(&input.base_url)?; - let _ = ideal_proxies_for_attempt(&input, 1)?; - let mut steps = Vec::new(); - add_step_with_progress( - &mut steps, - "locked config", - "ok", - "ideal NL/EUR Safari: NL bootstrap checkout -> VN checkout/update promotion -> NL provider/approve; attempts=20 concurrency=1 rebuild_attempts=5", - progress, - ); - - let mut last_error = None; - for attempt in 1..=MAX_REBUILD_ATTEMPTS { - let (checkout_proxy, promotion_proxy, checkout_index, promotion_index) = - ideal_proxies_for_attempt(&input, attempt)?; - if attempt > 1 { - add_step_with_progress( - &mut steps, - "rebuild checkout", - "info", - &format!( - "attempt {attempt}/{MAX_REBUILD_ATTEMPTS}; NL bootstrap -> VN promotion -> NL provider/approve retry" - ), - progress, - ); - } - match run_ideal_attempt( - transport, - &base, - &token, - &checkout_proxy, - &promotion_proxy, - checkout_index, - input.checkout_proxy_pool.len().max(1), - promotion_index, - input.promotion_proxy_pool.len().max(1), - attempt, - &mut steps, - progress, - ) - .await - { - Ok(mut output) => { - output.steps = steps; - return Ok(output); - } - Err(error) => { - let retryable = is_amount_policy_error(&error) - || is_chatgpt_approve_blocked_error(&error) - || retryable_stripe_provider_error(&error) - || retryable_transient_error(&error); - let detail = error.to_string(); - if !retryable || attempt >= MAX_REBUILD_ATTEMPTS { - return Err(error); - } - add_step_with_progress( - &mut steps, - "rebuild retry", - "warn", - &format!("{detail}; discarding current checkout and retrying"), - progress, - ); - last_error = Some(error); - } - } - } - Err(last_error.unwrap_or_else(|| { - ExtractError::BadResponse("extract failed after rebuild retries".to_string()) - })) -} - -fn ideal_proxies_for_attempt( - input: &ExtractInput, - attempt: usize, -) -> Result<(String, String, usize, usize), ExtractError> { - if !input.checkout_proxy_pool.is_empty() || !input.promotion_proxy_pool.is_empty() { - if input.checkout_proxy_pool.is_empty() { - return Err(ExtractError::MissingCheckoutProxyPool); - } - if input.promotion_proxy_pool.is_empty() { - return Err(ExtractError::MissingPromotionProxyPool); - } - let checkout_index = (attempt.saturating_sub(1)) % input.checkout_proxy_pool.len(); - let promotion_index = (attempt.saturating_sub(1)) % input.promotion_proxy_pool.len(); - return Ok(( - input.checkout_proxy_pool[checkout_index].clone(), - input.promotion_proxy_pool[promotion_index].clone(), - checkout_index + 1, - promotion_index + 1, - )); - } - - if input.proxy.trim().is_empty() { - return Err(ExtractError::BadResponse( - "proxy is required for strict NL-bootstrap / VN-promotion / NL-iDEAL extraction" - .to_string(), - )); - } - let attempt_proxy = proxy_seed_for_attempt(&input.proxy, attempt); - Ok(( - proxy_for_region(&attempt_proxy, CHECKOUT_REGION), - proxy_for_region(&attempt_proxy, PROMOTION_REGION), - 1, - 1, - )) -} - -async fn run_ideal_attempt( - transport: &mut T, - base: &EndpointBase, - token: &str, - checkout_proxy: &str, - promotion_proxy: &str, - checkout_proxy_index: usize, - checkout_proxy_count: usize, - promotion_proxy_index: usize, - promotion_proxy_count: usize, - attempt: usize, - steps: &mut Vec, - progress: Option<&ProgressSink>, -) -> Result { - let provider_proxy = checkout_proxy; - // Provider resolution and approval reuse the submitted Checkout route. - // approve_with_retries may refresh a rotating-proxy SID after an - // unsuccessful response, but it never switches to another configured pool. - let approve_proxy = checkout_proxy; - add_step_with_progress( - steps, - "proxy chain", - "ok", - &format!( - "attempt {attempt}/{MAX_REBUILD_ATTEMPTS}; checkout pool {checkout_proxy_index}/{checkout_proxy_count}; promotion pool {promotion_proxy_index}/{promotion_proxy_count}; provider/approve reuse checkout" - ), - progress, - ); - let device_id = Uuid::new_v4().to_string(); - let mut chatgpt_headers = chatgpt_headers(&token, &device_id); - let checkout = create_checkout( - transport, - &base, - &chatgpt_headers, - checkout_proxy, - LinkType::Ideal, - ) - .await?; - add_step_with_progress( - steps, - "checkout", - "ok", - &format!("NL bootstrap cs={}", checkout.cs_id), - progress, - ); - - let stripe_pk = if checkout.publishable_key.is_empty() { - DEFAULT_STRIPE_PK.to_string() - } else { - checkout.publishable_key.clone() - }; - let mut init = stripe_init( - transport, - &base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - LinkType::Ideal, - ) - .await?; - add_step_with_progress( - steps, - "stripe init", - "ok", - &format!( - "NL bootstrap amount={}; methods={}", - expected_amount(&init.payload), - stripe_init_payment_method_types(&init.payload).join(",") - ), - progress, - ); - ensure_ideal_is_offered(&init.payload, "NL bootstrap")?; - - // Do not create a second VN Checkout Session. Stripe would bind that - // session to card/link-only methods. Instead update the existing NL - // session through a VN exit; the official ChatGPT checkout/update API - // applies the eligible campaign without replacing the iDEAL method list. - update_checkout_promotion( - transport, - &base, - &chatgpt_headers, - &checkout, - promotion_proxy, - ) - .await?; - add_step_with_progress( - steps, - "VN promotion update", - "ok", - "checkout/update succeeded; reinitializing Stripe through NL", - progress, - ); - - init = stripe_init( - transport, - &base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - LinkType::Ideal, - ) - .await?; - let mut amount = expected_amount(&init.payload); - ensure_ideal_is_offered(&init.payload, "VN promotion refresh")?; - add_step_with_progress( - steps, - "VN promotion Stripe init", - "ok", - &format!( - "amount={amount}; methods={}", - stripe_init_payment_method_types(&init.payload).join(",") - ), - progress, - ); - - if amount.parse::().unwrap_or(0) > 50 { - return Err(ExtractError::BadResponse(format!( - "amount policy failed after VN promotion update: amount={amount}, allowed<= 50" - ))); - } - - let email = account_email_from_token(&token).unwrap_or_else(|| "buyer@example.com".to_string()); - update_ideal_checkout_taxes( - transport, - &base, - &chatgpt_headers, - &checkout, - &provider_proxy, - &email, - ) - .await?; - add_step_with_progress(steps, "iDEAL ChatGPT taxes", "ok", "country=NL", progress); - stripe_update_ideal_tax_region( - transport, - &base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - ) - .await?; - add_step_with_progress( - steps, - "iDEAL Stripe tax region", - "ok", - "country=NL", - progress, - ); - - // Taxes can change the expected_amount/init_checksum. Refresh the entire - // init payload before PM/confirm so Checkout does not reject the later - // approval with checkout_upcoming_invoice_mismatch. - init = stripe_init( - transport, - &base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - LinkType::Ideal, - ) - .await?; - amount = expected_amount(&init.payload); - ensure_ideal_is_offered(&init.payload, "tax refresh")?; - if amount.parse::().unwrap_or(0) > 50 { - return Err(ExtractError::BadResponse(format!( - "amount policy failed after iDEAL tax sync: amount={amount}, allowed<= 50" - ))); - } - add_step_with_progress( - steps, - "iDEAL tax Stripe init", - "ok", - &format!( - "amount={amount}; methods={}", - stripe_init_payment_method_types(&init.payload).join(",") - ), - progress, - ); - - let payment_method_id = create_ideal_payment_method( - transport, - &base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - &email, - ) - .await?; - add_step_with_progress(steps, "payment method", "ok", &payment_method_id, progress); - - let confirm_payload = stripe_confirm( - transport, - &base, - &checkout, - &init, - &stripe_pk, - &payment_method_id, - &init.stripe_hosted_url, - &provider_proxy, - ) - .await?; - add_step_with_progress(steps, "stripe confirm", "ok", "completed", progress); - - let stripe_redirect_url = match extract_redirect_to_url(&confirm_payload) { - Some(url) => url, - None => { - if confirm_requires_approval(&confirm_payload) { - chatgpt_headers.insert( - "referer".to_string(), - format!( - "https://chatgpt.com/checkout/{}/{}", - checkout.processor_entity, checkout.cs_id - ), - ); - let approval = approve_with_retries( - transport, - &base, - &chatgpt_headers, - &checkout, - approve_proxy, - LinkType::Ideal, - Some(ApproveRedirectPoll { - stripe_pk: &stripe_pk, - poll_proxy: &provider_proxy, - stage_region: PROVIDER_REGION, - }), - steps, - progress, - ) - .await?; - approval.stripe_redirect_url.ok_or_else(|| { - ExtractError::BadResponse( - "approve completed without stripe redirect url".to_string(), - ) - })? - } else { - poll_stripe_redirect( - transport, - &base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - LinkType::Ideal, - PROVIDER_REGION, - redirect_poll_attempts_for_link_type(LinkType::Ideal), - steps, - progress, - ) - .await? - } - } - }; - - let provider_redirect_url = resolve_external_redirect( - transport, - &base, - &stripe_redirect_url, - &provider_proxy, - LinkType::Ideal, - ) - .await?; - let long_url = if provider_redirect_url.is_empty() { - stripe_redirect_url.clone() - } else { - provider_redirect_url.clone() - }; - add_step_with_progress(steps, "provider redirect", "ok", &long_url, progress); - - Ok(ExtractOutput { - ok: true, - cs_id: checkout.cs_id, - billing_country: "NL".to_string(), - currency: "EUR".to_string(), - payment_method_id, - stripe_redirect_url, - provider_redirect_url, - long_url, - amount: amount.clone(), - amount_display: display_amount(&amount), - fallback: false, - provider_error: String::new(), - config: config_for_link_type(LinkType::Ideal), - steps: steps.clone(), - }) -} - -async fn extract_paypal_link_with_progress( - transport: &mut T, - input: ExtractInput, - progress: Option, -) -> Result { - let progress = progress.as_ref(); - let token = normalize_access_token(&input.access_token).ok_or(ExtractError::MissingToken)?; - let base = EndpointBase::new(&input.base_url)?; - if input.proxy.trim().is_empty() { - return Err(ExtractError::BadResponse( - "proxy is required for strict US-VN-TR-US PayPal extraction with US billing address" - .to_string(), - )); - } - let mut steps = Vec::new(); - add_step_with_progress( - &mut steps, - "locked config", - "ok", - "paypal US billing address / USD Chrome checkout US -> VN promotion -> TR provider -> US approve attempts=10 approve_attempts=1", - progress, - ); - - let mut last_error = None; - let mut last_fallback = None; - for attempt in 1..=PAYPAL_PROVIDER_MAX_ATTEMPTS { - let (checkout_proxy, promotion_proxy, provider_proxy, checkout_index, promotion_index, provider_index) = - paypal_proxies_for_attempt(&input, attempt)?; - if attempt > 1 { - add_step_with_progress( - &mut steps, - "rebuild checkout", - "info", - &format!("attempt {attempt}/{PAYPAL_PROVIDER_MAX_ATTEMPTS}; checkout pool #{checkout_index}; promotion pool #{promotion_index}; provider pool #{provider_index}; proxy chain {PAYPAL_CHECKOUT_REGION}->{PAYPAL_PROMOTION_REGION}->{PAYPAL_PROVIDER_REGION}->{PAYPAL_APPROVE_REGION} retry"), - progress, - ); - } - match run_paypal_attempt( - transport, - &base, - &token, - &checkout_proxy, - &promotion_proxy, - &provider_proxy, - attempt, - &mut steps, - progress, - ) - .await - { - Ok(mut output) => { - output.steps = steps; - return Ok(output); - } - Err(error) => { - if let Some(fallback) = paypal_fallback_from_error(&error) { - last_fallback = Some(fallback); - } - let retryable = is_amount_policy_error(&error) - || is_chatgpt_approve_blocked_error(&error) - || retryable_paypal_provider_error(&error) - || retryable_transient_error(&error); - let detail = error.to_string(); - if !retryable || attempt >= PAYPAL_PROVIDER_MAX_ATTEMPTS { - if let Some(fallback) = last_fallback { - add_step_with_progress( - &mut steps, - "provider fallback", - "warn", - &format!("{detail}; returning hosted checkout link"), - progress, - ); - return Ok(paypal_fallback_output(fallback, &steps, detail)); - } - return Err(error); - } - add_step_with_progress( - &mut steps, - "rebuild retry", - "warn", - &format!("{detail}; discarding current checkout and retrying"), - progress, - ); - last_error = Some(error); - } - } - } - if let Some(fallback) = last_fallback { - add_step_with_progress( - &mut steps, - "provider fallback", - "warn", - "paypal extract failed after retries; returning hosted checkout link", - progress, - ); - return Ok(paypal_fallback_output( - fallback, - &steps, - last_error - .map(|error| error.to_string()) - .unwrap_or_else(|| "paypal extract failed after retries".to_string()), - )); - } - Err(last_error.unwrap_or_else(|| { - ExtractError::BadResponse("paypal extract failed after retries".to_string()) - })) -} - -fn paypal_proxies_for_attempt( - input: &ExtractInput, - attempt: usize, -) -> Result<(String, String, String, usize, usize, usize), ExtractError> { - if !input.checkout_proxy_pool.is_empty() - || !input.promotion_proxy_pool.is_empty() - || !input.paypal_provider_proxy_pool.is_empty() - { - if input.checkout_proxy_pool.is_empty() { - return Err(ExtractError::MissingPaypalCheckoutProxyPool); - } - if input.promotion_proxy_pool.is_empty() { - return Err(ExtractError::MissingPaypalPromotionProxyPool); - } - if input.paypal_provider_proxy_pool.is_empty() { - return Err(ExtractError::MissingPaypalProviderProxyPool); - } - let checkout_index = (attempt.saturating_sub(1)) % input.checkout_proxy_pool.len(); - let promotion_index = (attempt.saturating_sub(1)) % input.promotion_proxy_pool.len(); - let provider_index = - (attempt.saturating_sub(1)) % input.paypal_provider_proxy_pool.len(); - return Ok(( - input.checkout_proxy_pool[checkout_index].clone(), - input.promotion_proxy_pool[promotion_index].clone(), - input.paypal_provider_proxy_pool[provider_index].clone(), - checkout_index + 1, - promotion_index + 1, - provider_index + 1, - )); - } - - if input.proxy.trim().is_empty() { - return Err(ExtractError::BadResponse( - "proxy is required for strict US-VN-TR-US PayPal extraction with US billing address" - .to_string(), - )); - } - Ok(( - input.proxy.clone(), - input.proxy.clone(), - input.proxy.clone(), - 1, - 1, - 1, - )) -} - -async fn run_paypal_attempt( - transport: &mut T, - base: &EndpointBase, - token: &str, - checkout_proxy_seed: &str, - promotion_proxy_seed: &str, - provider_proxy_seed: &str, - attempt: usize, - steps: &mut Vec, - progress: Option<&ProgressSink>, -) -> Result { - let attempt_checkout_proxy = proxy_seed_for_attempt(checkout_proxy_seed, attempt); - let attempt_promotion_proxy = proxy_seed_for_attempt(promotion_proxy_seed, attempt); - let attempt_provider_proxy = proxy_seed_for_attempt(provider_proxy_seed, attempt); - let checkout_proxy = proxy_for_region(&attempt_checkout_proxy, PAYPAL_CHECKOUT_REGION); - let promotion_proxy = proxy_for_region(&attempt_promotion_proxy, PAYPAL_PROMOTION_REGION); - let provider_proxy = proxy_for_region(&attempt_provider_proxy, PAYPAL_PROVIDER_REGION); - let approve_proxy = - proxy_with_fresh_sid(&proxy_for_region(&attempt_checkout_proxy, PAYPAL_APPROVE_REGION)); - add_step_with_progress( - steps, - "proxy chain", - "ok", - &format!("attempt {attempt}/{PAYPAL_PROVIDER_MAX_ATTEMPTS}; checkout={PAYPAL_CHECKOUT_REGION}; promotion={PAYPAL_PROMOTION_REGION}; provider={PAYPAL_PROVIDER_REGION}; approve={PAYPAL_APPROVE_REGION}"), - progress, - ); - - let device_id = Uuid::new_v4().to_string(); - let mut chatgpt_headers = chatgpt_headers_for(token, &device_id, LinkType::Paypal); - let checkout = create_checkout( - transport, - base, - &chatgpt_headers, - &checkout_proxy, - LinkType::Paypal, - ) - .await?; - add_step_with_progress(steps, "checkout", "ok", &checkout.cs_id, progress); - - update_checkout_promotion( - transport, - base, - &chatgpt_headers, - &checkout, - &promotion_proxy, - ) - .await?; - add_step_with_progress( - steps, - "VN promotion update", - "ok", - "promotion applied before PayPal; reinitializing Stripe through TR", - progress, - ); - - let stripe_pk = if checkout.publishable_key.is_empty() { - DEFAULT_STRIPE_PK.to_string() - } else { - checkout.publishable_key.clone() - }; - let init = stripe_init( - transport, - base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - LinkType::Paypal, - ) - .await?; - add_step_with_progress( - steps, - "VN promotion Stripe init", - "ok", - &init.stripe_hosted_url, - progress, - ); - - let amount = expected_amount(&init.payload); - if amount.parse::().unwrap_or(0) > 50 { - let error = ExtractError::BadResponse(format!( - "amount policy failed: amount={amount}, allowed<= 50" - )); - return Err(paypal_provider_failed(error, &checkout, &init, &amount, "")); - } - - let email = account_email_from_token(token).unwrap_or_else(|| { - format!( - "buyer.{}@example.com", - &Uuid::new_v4().simple().to_string()[..12] - ) - }); - let paypal_billing_country = paypal_billing_country(); - stripe_update_paypal_tax_region( - transport, - base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - paypal_billing_country, - ) - .await - .map_err(|error| paypal_provider_failed(error, &checkout, &init, &amount, ""))?; - add_step_with_progress( - steps, - "paypal tax region", - "ok", - &format!( - "country={}; state={}", - paypal_billing_country, - paypal_billing_state(paypal_billing_country).unwrap_or("-") - ), - progress, - ); - - let ctx = stripe_context(&init.payload, LinkType::Paypal); - let inline_confirm = attempt % 2 == 0; - add_step_with_progress( - steps, - "payment method", - "info", - if inline_confirm { - "strategy=inline; submit payment_method_data in confirm" - } else { - "strategy=baseline; create PayPal payment_method before confirm" - }, - progress, - ); - let (payment_method_id, confirm_payload) = if inline_confirm { - let payload = stripe_confirm_paypal_inline( - transport, - base, - &checkout, - &ctx, - &stripe_pk, - &init.stripe_hosted_url, - &provider_proxy, - &email, - paypal_billing_country, - ) - .await - .map_err(|error| paypal_provider_failed(error, &checkout, &init, &amount, ""))?; - let pm_id = find_nested_payment_method_id(&payload).unwrap_or_default(); - add_step_with_progress( - steps, - "payment method", - "ok", - if pm_id.is_empty() { - "inline confirm completed" - } else { - &pm_id - }, - progress, - ); - (pm_id, payload) - } else { - let pm_id = create_paypal_payment_method( - transport, - base, - &checkout.cs_id, - &stripe_pk, - &provider_proxy, - &email, - paypal_billing_country, - &ctx, - ) - .await - .map_err(|error| paypal_provider_failed(error, &checkout, &init, &amount, ""))?; - add_step_with_progress(steps, "payment method", "ok", &pm_id, progress); - let payload = stripe_confirm_paypal( - transport, - base, - &checkout, - &ctx, - &stripe_pk, - &pm_id, - &init.stripe_hosted_url, - &provider_proxy, - ) - .await - .map_err(|error| paypal_provider_failed(error, &checkout, &init, &amount, &pm_id))?; - (pm_id, payload) - }; - add_step_with_progress(steps, "stripe confirm", "ok", "completed", progress); - - let stripe_redirect_url = match extract_redirect_to_url(&confirm_payload) { - Some(url) => url, - None => { - let mut effective_approve_proxy = approve_proxy.clone(); - if let Some(cached_proxy) = - approved_proxy_for_request(token, LinkType::Paypal, PAYPAL_APPROVE_REGION) - { - add_step_with_progress( - steps, - "approved proxy cache", - "ok", - &format!( - "using cached approve/poll proxy: {}", - proxy_summary(&cached_proxy) - ), - progress, - ); - effective_approve_proxy = cached_proxy; - } - if confirm_requires_approval(&confirm_payload) { - chatgpt_headers.insert( - "referer".to_string(), - format!( - "https://chatgpt.com/checkout/{}/{}", - checkout.processor_entity, checkout.cs_id - ), - ); - let approval = approve_with_retries( - transport, - base, - &chatgpt_headers, - &checkout, - &effective_approve_proxy, - LinkType::Paypal, - Some(ApproveRedirectPoll { - stripe_pk: &stripe_pk, - poll_proxy: &effective_approve_proxy, - stage_region: PAYPAL_APPROVE_REGION, - }), - steps, - progress, - ) - .await - .map_err(|error| { - paypal_provider_failed(error, &checkout, &init, &amount, &payment_method_id) - })?; - approval.stripe_redirect_url.ok_or_else(|| { - paypal_provider_failed( - ExtractError::BadResponse( - "approve completed without stripe redirect url".to_string(), - ), - &checkout, - &init, - &amount, - &payment_method_id, - ) - })? - } else { - poll_stripe_redirect( - transport, - base, - &checkout.cs_id, - &stripe_pk, - &effective_approve_proxy, - LinkType::Paypal, - PAYPAL_APPROVE_REGION, - redirect_poll_attempts_for_link_type(LinkType::Paypal), - steps, - progress, - ) - .await - .map_err(|error| { - paypal_provider_failed(error, &checkout, &init, &amount, &payment_method_id) - })? - } - } - }; - - let provider_redirect_url = resolve_external_redirect( - transport, - base, - &stripe_redirect_url, - &provider_proxy, - LinkType::Paypal, - ) - .await - .map_err(|error| { - paypal_provider_failed(error, &checkout, &init, &amount, &payment_method_id) - })?; - let long_url = if provider_redirect_url.is_empty() { - stripe_redirect_url.clone() - } else { - provider_redirect_url.clone() - }; - add_step_with_progress(steps, "provider redirect", "ok", &long_url, progress); - - Ok(ExtractOutput { - ok: true, - cs_id: checkout.cs_id, - billing_country: paypal_billing_country.to_string(), - currency: "USD".to_string(), - payment_method_id, - stripe_redirect_url, - provider_redirect_url, - long_url, - amount: amount.clone(), - amount_display: display_amount_for(&amount, "USD"), - fallback: false, - provider_error: String::new(), - config: config_for_link_type(LinkType::Paypal), - steps: steps.clone(), - }) -} - -#[derive(Debug, Clone)] -struct EndpointBase { - raw: String, - mock: bool, -} - -impl EndpointBase { - fn new(value: &str) -> Result { - let supplied = value.trim().trim_end_matches('/'); - if supplied.is_empty() { - return Ok(Self { - raw: "https://chatgpt.com".to_string(), - mock: false, - }); - } - let parsed = - Url::parse(supplied).map_err(|_| ExtractError::UnsafeBaseUrl(supplied.to_string()))?; - let official_chatgpt = matches!(parsed.host(), Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("chatgpt.com")); - if official_chatgpt { - return Ok(Self { - raw: supplied.to_string(), - mock: false, - }); - } - if is_local_base_host(&parsed) { - return Ok(Self { - raw: supplied.to_string(), - mock: true, - }); - } - Err(ExtractError::UnsafeBaseUrl(supplied.to_string())) - } - - fn chatgpt(&self, path: &str) -> String { - if self.mock { - format!("{}{}", self.raw, path) - } else { - format!("https://chatgpt.com{path}") - } - } - - fn stripe(&self, path: &str) -> String { - if self.mock { - format!("{}{}", self.raw, path) - } else { - format!("https://api.stripe.com{path}") - } - } - - fn redirect(&self, url: &str) -> String { - if !self.mock { - return url.to_string(); - } - match Url::parse(url) { - Ok(parsed) => format!("{}{}", self.raw, parsed.path()), - Err(_) => url.to_string(), - } - } -} - -fn is_local_base_host(parsed: &Url) -> bool { - match parsed.host() { - Some(Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), - None => false, - } -} - -#[derive(Debug)] -struct Checkout { - cs_id: String, - processor_entity: String, - publishable_key: String, -} - -#[derive(Debug)] -struct InitPayload { - stripe_hosted_url: String, - payload: Value, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct PaypalFallback { - cs_id: String, - processor_entity: String, - stripe_hosted_url: String, - amount: String, - payment_method_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -struct ApprovedProxyEntry { - proxy: String, - region: String, - link_type: String, - account_key: String, - saved_at: String, - proxy_summary: String, -} - -#[derive(Debug, Clone)] -struct StripeContext { - stripe_js_id: String, - client_session_id: String, - guid: String, - muid: String, - sid: String, - elements_session_id: String, - elements_session_config_id: String, - config_id: String, - init_checksum: String, - checkout_amount: String, - locale: String, - runtime_version: String, - stripe_version: String, -} - -fn add_step_with_progress( - steps: &mut Vec, - name: &str, - status: &str, - detail: &str, - progress: Option<&ProgressSink>, -) { - let step = Step { - name: name.to_string(), - status: status.to_string(), - detail: detail.to_string(), - }; - if let Some(progress) = progress { - (progress.as_ref())(step.clone()); - } - steps.push(step); -} - -fn normalize_access_token(raw: &str) -> Option { - let trimmed = raw - .trim() - .strip_prefix("Bearer ") - .unwrap_or(raw.trim()) - .trim(); - if trimmed.is_empty() { - return None; - } - if trimmed.starts_with('{') || trimmed.starts_with('[') { - if let Ok(value) = serde_json::from_str::(trimmed) { - return find_token(&value); - } - return None; - } - Some(trimmed.to_string()) -} - -fn find_token(value: &Value) -> Option { - match value { - Value::String(text) => normalize_access_token(text), - Value::Array(items) => items.iter().find_map(find_token), - Value::Object(map) => { - for key in ["accessToken", "access_token", "token"] { - if let Some(token) = map.get(key).and_then(find_token) { - return Some(token); - } - } - map.values().find_map(find_token) - } - _ => None, - } -} - -fn jwt_payload(token: &str) -> Option { - let payload = token.split('.').nth(1)?; - let decoded = URL_SAFE_NO_PAD.decode(payload.as_bytes()).ok()?; - serde_json::from_slice(&decoded).ok() -} - -fn account_email_from_token(token: &str) -> Option { - let value = jwt_payload(token)?; - let profile = value - .get("https://api.openai.com/profile") - .and_then(Value::as_object); - if let Some(email) = profile - .and_then(|profile| { - profile - .get("email") - .or_else(|| profile.get("email_address")) - }) - .and_then(Value::as_str) - .map(str::trim) - .filter(|email| email.contains('@')) - { - return Some(email.to_string()); - } - let direct = value - .get("email") - .and_then(Value::as_str) - .or_else(|| value.get("preferred_username").and_then(Value::as_str)); - direct - .map(str::trim) - .filter(|email| email.contains('@')) - .map(ToOwned::to_owned) -} - -fn chatgpt_headers(token: &str, device_id: &str) -> BTreeMap { - chatgpt_headers_for(token, device_id, LinkType::Ideal) -} - -fn chatgpt_headers_for( - token: &str, - device_id: &str, - link_type: LinkType, -) -> BTreeMap { - let mut headers = BTreeMap::new(); - let (user_agent, accept_language, browser_locale, sec_ch_ua, platform) = match link_type { - LinkType::Ideal => ( - APPLE_SAFARI_USER_AGENT, - ACCEPT_LANGUAGE, - BROWSER_LOCALE, - "\"Safari\";v=\"17\", \"Not.A/Brand\";v=\"8\"", - "\"macOS\"", - ), - LinkType::Paypal => ( - PAYPAL_USER_AGENT, - PAYPAL_ACCEPT_LANGUAGE, - PAYPAL_BROWSER_LOCALE, - "\"Google Chrome\";v=\"147\", \"Chromium\";v=\"147\", \"Not.A/Brand\";v=\"24\"", - "\"Windows\"", - ), - }; - headers.insert("user-agent".to_string(), user_agent.to_string()); - headers.insert("accept".to_string(), "*/*".to_string()); - headers.insert("accept-language".to_string(), accept_language.to_string()); - headers.insert("authorization".to_string(), format!("Bearer {token}")); - headers.insert("origin".to_string(), "https://chatgpt.com".to_string()); - headers.insert("referer".to_string(), "https://chatgpt.com/".to_string()); - headers.insert("content-type".to_string(), "application/json".to_string()); - headers.insert("oai-device-id".to_string(), device_id.to_string()); - headers.insert("oai-language".to_string(), browser_locale.to_string()); - headers.insert("oai-session-id".to_string(), Uuid::new_v4().to_string()); - headers.insert( - "oai-client-version".to_string(), - CHATGPT_CLIENT_VERSION.to_string(), - ); - headers.insert( - "oai-client-build-number".to_string(), - CHATGPT_CLIENT_BUILD_NUMBER.to_string(), - ); - headers.insert("sec-fetch-dest".to_string(), "empty".to_string()); - headers.insert("sec-fetch-mode".to_string(), "cors".to_string()); - headers.insert("sec-fetch-site".to_string(), "same-origin".to_string()); - headers.insert("sec-ch-ua".to_string(), sec_ch_ua.to_string()); - headers.insert("sec-ch-ua-mobile".to_string(), "?0".to_string()); - headers.insert("sec-ch-ua-platform".to_string(), platform.to_string()); - headers.insert("cookie".to_string(), format!("oai-did={device_id}")); - headers -} - -fn stripe_headers() -> BTreeMap { - stripe_headers_for(LinkType::Ideal) -} - -fn stripe_headers_for(link_type: LinkType) -> BTreeMap { - let mut headers = BTreeMap::new(); - let (user_agent, accept_language) = match link_type { - LinkType::Ideal => (APPLE_SAFARI_USER_AGENT, ACCEPT_LANGUAGE), - LinkType::Paypal => (PAYPAL_USER_AGENT, PAYPAL_ACCEPT_LANGUAGE), - }; - headers.insert("user-agent".to_string(), user_agent.to_string()); - headers.insert("accept-language".to_string(), accept_language.to_string()); - headers -} - -async fn create_checkout( - transport: &mut T, - base: &EndpointBase, - headers: &BTreeMap, - checkout_proxy: &str, - link_type: LinkType, -) -> Result { - let config = config_for_link_type(link_type); - let body = json!({ - "entry_point": "all_plans_pricing_modal", - "plan_name": "chatgptplusplan", - "billing_details": { "country": config.billing_country, "currency": config.currency }, - "promo_campaign": { "promo_campaign_id": "plus-1-month-free", "is_coupon_from_query_param": false }, - "checkout_ui_mode": config.checkout_ui_mode - }); - let mut request_headers = headers.clone(); - request_headers.insert( - "x-openai-target-path".to_string(), - "/backend-api/payments/checkout".to_string(), - ); - request_headers.insert( - "x-openai-target-route".to_string(), - "/backend-api/payments/checkout".to_string(), - ); - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.chatgpt("/backend-api/payments/checkout"), - headers: request_headers, - body: RequestBody::Json(body), - stage_proxy: format!("checkout:{}", config.checkout_proxy_region), - proxy_url: checkout_proxy.to_string(), - }) - .await?; - let payload = json_response(response, "checkout create")?; - let cs_id = first_string(&payload, &["checkout_session_id", "session_id", "id"]) - .filter(|value| value.starts_with("cs_")) - .ok_or_else(|| { - ExtractError::BadResponse(format!("checkout response missing cs_id: {payload}")) - })?; - Ok(Checkout { - cs_id, - processor_entity: first_string(&payload, &["processor_entity", "processorEntity"]) - .unwrap_or_else(|| "openai_ie".to_string()), - publishable_key: first_string(&payload, &["publishable_key"]).unwrap_or_default(), - }) -} - -async fn stripe_init( - transport: &mut T, - base: &EndpointBase, - cs_id: &str, - stripe_pk: &str, - provider_proxy: &str, - link_type: LinkType, -) -> Result { - let mut form = BTreeMap::new(); - match link_type { - LinkType::Ideal => { - form.insert("browser_locale".to_string(), BROWSER_LOCALE.to_string()); - form.insert("browser_timezone".to_string(), BROWSER_TIMEZONE.to_string()); - form.insert( - "elements_session_client[client_betas][0]".to_string(), - "custom_checkout_server_updates_1".to_string(), - ); - form.insert( - "elements_session_client[client_betas][1]".to_string(), - "custom_checkout_manual_approval_1".to_string(), - ); - form.insert( - "elements_session_client[elements_init_source]".to_string(), - "custom_checkout".to_string(), - ); - form.insert( - "elements_session_client[referrer_host]".to_string(), - "chatgpt.com".to_string(), - ); - form.insert( - "elements_session_client[stripe_js_id]".to_string(), - Uuid::new_v4().to_string(), - ); - form.insert( - "elements_session_client[locale]".to_string(), - ELEMENTS_LOCALE.to_string(), - ); - form.insert( - "elements_session_client[is_aggregation_expected]".to_string(), - "false".to_string(), - ); - form.insert( - "elements_options_client[saved_payment_method][enable_save]".to_string(), - "never".to_string(), - ); - form.insert( - "elements_options_client[saved_payment_method][enable_redisplay]".to_string(), - "never".to_string(), - ); - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert( - "_stripe_version".to_string(), - STRIPE_VERSION_FULL.to_string(), - ); - } - LinkType::Paypal => { - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert("eid".to_string(), "NA".to_string()); - form.insert( - "browser_locale".to_string(), - PAYPAL_BROWSER_LOCALE.to_string(), - ); - form.insert( - "browser_timezone".to_string(), - PAYPAL_BROWSER_TIMEZONE.to_string(), - ); - form.insert("redirect_type".to_string(), "url".to_string()); - } - } - let config = config_for_link_type(link_type); - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{cs_id}/init")), - headers: stripe_headers_for(link_type), - body: RequestBody::Form(form), - stage_proxy: format!("provider:{}", config.provider_proxy_region), - proxy_url: provider_proxy.to_string(), - }) - .await?; - let payload = json_response(response, "stripe init")?; - let stripe_hosted_url = first_string(&payload, &["stripe_hosted_url"]).ok_or_else(|| { - ExtractError::BadResponse(format!( - "stripe init response missing stripe_hosted_url: {payload}" - )) - })?; - Ok(InitPayload { - stripe_hosted_url, - payload, - }) -} - -async fn update_checkout_promotion( - transport: &mut T, - base: &EndpointBase, - headers: &BTreeMap, - checkout: &Checkout, - promotion_proxy: &str, -) -> Result<(), ExtractError> { - let path = "/backend-api/payments/checkout/update"; - let referer = format!( - "https://chatgpt.com/checkout/{}/{}", - checkout.processor_entity, checkout.cs_id - ); - let body = json!({ - "checkout_session_id": checkout.cs_id, - "processor_entity": checkout.processor_entity, - "plan_name": "chatgptplusplan", - "price_interval": "month", - "seat_quantity": 1, - "promo_campaign": { - "promo_campaign_id": "plus-1-month-free", - "is_coupon_from_query_param": false, - }, - }); - let payload = json_response( - transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.chatgpt(path), - headers: target_headers(headers, path, &referer), - body: RequestBody::Json(body), - stage_proxy: format!("promotion:{PROMOTION_REGION}"), - proxy_url: promotion_proxy.to_string(), - }) - .await?, - "chatgpt checkout promotion update", - )?; - if payload.get("success").and_then(Value::as_bool) == Some(false) { - return Err(ExtractError::BadResponse(format!( - "chatgpt checkout promotion update rejected: {payload}" - ))); - } - Ok(()) -} - -async fn update_ideal_checkout_taxes( - transport: &mut T, - base: &EndpointBase, - headers: &BTreeMap, - checkout: &Checkout, - provider_proxy: &str, - email: &str, -) -> Result<(), ExtractError> { - let path = "/backend-api/payments/checkout/taxes"; - let referer = format!( - "https://chatgpt.com/checkout/{}/{}", - checkout.processor_entity, checkout.cs_id - ); - let body = json!({ - "checkout_session_id": checkout.cs_id, - "checkout_email": email, - "billing_country": "NL", - "billing_name": IDEAL_BILLING_NAME, - "currency": "EUR", - "tax_id": Value::Null, - "processor_entity": checkout.processor_entity, - "billing_address": { - "line1": IDEAL_BILLING_LINE1, - "city": IDEAL_BILLING_CITY, - "country": "NL", - "postal_code": IDEAL_BILLING_POSTAL_CODE, - }, - }); - let _ = json_response( - transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.chatgpt(path), - headers: target_headers(headers, path, &referer), - body: RequestBody::Json(body), - stage_proxy: format!("provider:{PROVIDER_REGION}"), - proxy_url: provider_proxy.to_string(), - }) - .await?, - "chatgpt checkout taxes", - )?; - Ok(()) -} - -async fn stripe_update_ideal_tax_region( - transport: &mut T, - base: &EndpointBase, - cs_id: &str, - stripe_pk: &str, - provider_proxy: &str, -) -> Result<(), ExtractError> { - let mut form = BTreeMap::new(); - form.insert("eid".to_string(), "NA".to_string()); - form.insert("tax_region[country]".to_string(), "NL".to_string()); - form.insert( - "tax_region[postal_code]".to_string(), - IDEAL_BILLING_POSTAL_CODE.to_string(), - ); - form.insert( - "tax_region[line1]".to_string(), - IDEAL_BILLING_LINE1.to_string(), - ); - form.insert( - "tax_region[city]".to_string(), - IDEAL_BILLING_CITY.to_string(), - ); - form.insert("key".to_string(), stripe_pk.to_string()); - let _ = json_response( - transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{cs_id}")), - headers: stripe_headers(), - body: RequestBody::Form(form), - stage_proxy: format!("provider:{PROVIDER_REGION}"), - proxy_url: provider_proxy.to_string(), - }) - .await?, - "stripe ideal tax region", - )?; - Ok(()) -} - -fn stripe_init_payment_method_types(payload: &Value) -> Vec { - fn push(value: &Value, methods: &mut Vec) { - match value { - Value::String(value) => { - let method = value.trim().to_ascii_lowercase(); - if !method.is_empty() && !methods.iter().any(|item| item == &method) { - methods.push(method); - } - } - Value::Array(values) => { - for value in values { - push(value, methods); - } - } - Value::Object(values) => { - if let Some(kind) = values.get("type") { - push(kind, methods); - } - } - _ => {} - } - } - - let mut methods = Vec::new(); - for source in [Some(payload), payload.get("elements_options")] - .into_iter() - .flatten() - { - for key in [ - "payment_method_types", - "ordered_payment_method_types", - "payment_method_specs", - "custom_payment_methods", - ] { - if let Some(value) = source.get(key) { - push(value, &mut methods); - } - } - } - methods -} - -fn ensure_ideal_is_offered(payload: &Value, phase: &str) -> Result<(), ExtractError> { - let methods = stripe_init_payment_method_types(payload); - if !methods.is_empty() && !methods.iter().any(|method| method == "ideal") { - return Err(ExtractError::BadResponse(format!( - "{phase} checkout does not offer ideal; available payment methods: {}", - methods.join(", ") - ))); - } - Ok(()) -} - -async fn create_ideal_payment_method( - transport: &mut T, - base: &EndpointBase, - cs_id: &str, - stripe_pk: &str, - provider_proxy: &str, - email: &str, -) -> Result { - let mut form = BTreeMap::new(); - form.insert( - "billing_details[name]".to_string(), - IDEAL_BILLING_NAME.to_string(), - ); - form.insert("billing_details[email]".to_string(), email.to_string()); - form.insert( - "billing_details[address][country]".to_string(), - "NL".to_string(), - ); - form.insert( - "billing_details[address][line1]".to_string(), - IDEAL_BILLING_LINE1.to_string(), - ); - form.insert( - "billing_details[address][city]".to_string(), - IDEAL_BILLING_CITY.to_string(), - ); - form.insert( - "billing_details[address][postal_code]".to_string(), - IDEAL_BILLING_POSTAL_CODE.to_string(), - ); - form.insert("type".to_string(), "ideal".to_string()); - form.insert( - "client_attribution_metadata[checkout_session_id]".to_string(), - cs_id.to_string(), - ); - form.insert("key".to_string(), stripe_pk.to_string()); - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe("/v1/payment_methods"), - headers: stripe_headers(), - body: RequestBody::Form(form), - stage_proxy: "provider:NL".to_string(), - proxy_url: provider_proxy.to_string(), - }) - .await?; - let payload = json_response(response, "stripe payment_methods")?; - first_string(&payload, &["id"]) - .filter(|id| id.starts_with("pm_")) - .ok_or_else(|| { - ExtractError::BadResponse(format!("stripe payment_methods bad response: {payload}")) - }) -} - -async fn stripe_update_paypal_tax_region( - transport: &mut T, - base: &EndpointBase, - cs_id: &str, - stripe_pk: &str, - provider_proxy: &str, - _billing_country: &str, -) -> Result<(), ExtractError> { - let billing_country = paypal_billing_country(); - let mut updates = vec![vec![ - ("eid".to_string(), "NA".to_string()), - ( - "tax_region[country]".to_string(), - billing_country.to_string(), - ), - ("key".to_string(), stripe_pk.to_string()), - ]]; - if let Some(state) = paypal_billing_state(billing_country) { - updates.push(vec![ - ("eid".to_string(), "NA".to_string()), - ( - "tax_region[country]".to_string(), - billing_country.to_string(), - ), - ("tax_region[state]".to_string(), state.to_string()), - ("key".to_string(), stripe_pk.to_string()), - ]); - } - for update in updates { - let form = update.into_iter().collect::>(); - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{cs_id}")), - headers: stripe_headers_for(LinkType::Paypal), - body: RequestBody::Form(form), - stage_proxy: format!("provider:{PAYPAL_PROVIDER_REGION}"), - proxy_url: provider_proxy.to_string(), - }) - .await?; - let _ = json_response(response, "stripe paypal tax region")?; - } - Ok(()) -} - -async fn create_paypal_payment_method( - transport: &mut T, - base: &EndpointBase, - cs_id: &str, - stripe_pk: &str, - provider_proxy: &str, - email: &str, - billing_country: &str, - ctx: &StripeContext, -) -> Result { - let mut form = paypal_billing_form("billing_details", email, billing_country); - form.insert("type".to_string(), "paypal".to_string()); - form.insert("guid".to_string(), ctx.guid.clone()); - form.insert("muid".to_string(), ctx.muid.clone()); - form.insert("sid".to_string(), ctx.sid.clone()); - form.insert("_stripe_version".to_string(), ctx.stripe_version.clone()); - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert( - "payment_user_agent".to_string(), - format!( - "stripe.js/{}; stripe-js-v3/{}; checkout", - ctx.runtime_version, ctx.runtime_version - ), - ); - form.insert( - "client_attribution_metadata[client_session_id]".to_string(), - ctx.client_session_id.clone(), - ); - form.insert( - "client_attribution_metadata[checkout_session_id]".to_string(), - cs_id.to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_source]".to_string(), - "checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_version]".to_string(), - "custom_checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[payment_method_selection_flow]".to_string(), - "automatic".to_string(), - ); - form.insert( - "client_attribution_metadata[checkout_config_id]".to_string(), - ctx.config_id.clone(), - ); - - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe("/v1/payment_methods"), - headers: stripe_headers_for(LinkType::Paypal), - body: RequestBody::Form(form), - stage_proxy: format!("provider:{PAYPAL_PROVIDER_REGION}"), - proxy_url: provider_proxy.to_string(), - }) - .await?; - let payload = json_response(response, "stripe payment_methods")?; - first_string(&payload, &["id"]) - .filter(|id| id.starts_with("pm_")) - .ok_or_else(|| { - ExtractError::BadResponse(format!("stripe payment_methods bad response: {payload}")) - }) -} - -async fn stripe_confirm_paypal( - transport: &mut T, - base: &EndpointBase, - checkout: &Checkout, - ctx: &StripeContext, - stripe_pk: &str, - payment_method_id: &str, - stripe_hosted_url: &str, - provider_proxy: &str, -) -> Result { - let mut form = BTreeMap::new(); - form.insert("eid".to_string(), "NA".to_string()); - form.insert("payment_method".to_string(), payment_method_id.to_string()); - form.insert("expected_amount".to_string(), ctx.checkout_amount.clone()); - form.insert( - "expected_payment_method_type".to_string(), - "paypal".to_string(), - ); - form.insert( - "return_url".to_string(), - paypal_confirm_return_url( - &checkout.cs_id, - &checkout.processor_entity, - stripe_hosted_url, - ), - ); - form.insert("_stripe_version".to_string(), ctx.stripe_version.clone()); - form.insert("guid".to_string(), ctx.guid.clone()); - form.insert("muid".to_string(), ctx.muid.clone()); - form.insert("sid".to_string(), ctx.sid.clone()); - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert("version".to_string(), ctx.runtime_version.clone()); - form.insert("init_checksum".to_string(), ctx.init_checksum.clone()); - form.insert( - "client_attribution_metadata[client_session_id]".to_string(), - ctx.client_session_id.clone(), - ); - form.insert( - "client_attribution_metadata[checkout_session_id]".to_string(), - checkout.cs_id.clone(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_source]".to_string(), - "checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_version]".to_string(), - "custom_checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[payment_method_selection_flow]".to_string(), - "automatic".to_string(), - ); - form.insert( - "client_attribution_metadata[checkout_config_id]".to_string(), - ctx.config_id.clone(), - ); - form.insert("link_brand".to_string(), "link".to_string()); - apply_stripe_fingerprint(&mut form, LinkType::Paypal); - - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{}/confirm", checkout.cs_id)), - headers: stripe_headers_for(LinkType::Paypal), - body: RequestBody::Form(form), - stage_proxy: format!("provider:{PAYPAL_PROVIDER_REGION}"), - proxy_url: provider_proxy.to_string(), - }) - .await?; - if let Some(url) = extract_paypal_ba_approve_url_from_text(&response.body) { - return Ok(json!({ "_ba_approve_url": url, "_raw_status": response.status })); - } - json_response(response, "stripe confirm") -} - -async fn stripe_confirm_paypal_inline( - transport: &mut T, - base: &EndpointBase, - checkout: &Checkout, - ctx: &StripeContext, - stripe_pk: &str, - stripe_hosted_url: &str, - provider_proxy: &str, - email: &str, - billing_country: &str, -) -> Result { - let mut form = BTreeMap::new(); - form.insert("guid".to_string(), ctx.guid.clone()); - form.insert("muid".to_string(), ctx.muid.clone()); - form.insert("sid".to_string(), ctx.sid.clone()); - form.insert( - "payment_method_data[type]".to_string(), - "paypal".to_string(), - ); - form.insert("init_checksum".to_string(), ctx.init_checksum.clone()); - form.insert("version".to_string(), ctx.runtime_version.clone()); - form.insert("expected_amount".to_string(), ctx.checkout_amount.clone()); - form.insert( - "expected_payment_method_type".to_string(), - "paypal".to_string(), - ); - form.insert( - "return_url".to_string(), - stripe_confirm_return_url( - &checkout.cs_id, - &checkout.processor_entity, - stripe_hosted_url, - ), - ); - form.insert( - "elements_session_client[session_id]".to_string(), - ctx.elements_session_id.clone(), - ); - form.insert( - "elements_session_client[locale]".to_string(), - ctx.locale.clone(), - ); - form.insert( - "elements_session_client[referrer_host]".to_string(), - "chatgpt.com".to_string(), - ); - form.insert( - "elements_session_client[is_aggregation_expected]".to_string(), - "false".to_string(), - ); - form.insert( - "elements_session_client[elements_init_source]".to_string(), - "custom_checkout".to_string(), - ); - form.insert( - "elements_session_client[stripe_js_id]".to_string(), - ctx.stripe_js_id.clone(), - ); - form.insert( - "elements_session_client[client_betas][0]".to_string(), - "custom_checkout_server_updates_1".to_string(), - ); - form.insert( - "elements_session_client[client_betas][1]".to_string(), - "custom_checkout_manual_approval_1".to_string(), - ); - form.insert( - "elements_options_client[saved_payment_method][enable_save]".to_string(), - "never".to_string(), - ); - form.insert( - "elements_options_client[saved_payment_method][enable_redisplay]".to_string(), - "never".to_string(), - ); - form.insert( - "client_attribution_metadata[client_session_id]".to_string(), - ctx.stripe_js_id.clone(), - ); - form.insert( - "client_attribution_metadata[checkout_session_id]".to_string(), - checkout.cs_id.clone(), - ); - form.insert( - "client_attribution_metadata[checkout_config_id]".to_string(), - ctx.config_id.clone(), - ); - form.insert( - "client_attribution_metadata[elements_session_id]".to_string(), - ctx.elements_session_id.clone(), - ); - form.insert( - "client_attribution_metadata[elements_session_config_id]".to_string(), - ctx.elements_session_config_id.clone(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_source]".to_string(), - "checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_subtype]".to_string(), - "payment-element".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_version]".to_string(), - "custom".to_string(), - ); - form.insert( - "client_attribution_metadata[payment_intent_creation_flow]".to_string(), - "deferred".to_string(), - ); - form.insert( - "client_attribution_metadata[payment_method_selection_flow]".to_string(), - "automatic".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_additional_elements][0]".to_string(), - "payment".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_additional_elements][1]".to_string(), - "address".to_string(), - ); - form.insert( - "consent[terms_of_service]".to_string(), - "accepted".to_string(), - ); - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert( - "_stripe_version".to_string(), - STRIPE_VERSION_FULL.to_string(), - ); - form.extend(paypal_billing_form( - "payment_method_data[billing_details]", - email, - billing_country, - )); - - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{}/confirm", checkout.cs_id)), - headers: stripe_headers_for(LinkType::Paypal), - body: RequestBody::Form(form), - stage_proxy: format!("provider:{PAYPAL_PROVIDER_REGION}"), - proxy_url: provider_proxy.to_string(), - }) - .await?; - if let Some(url) = extract_paypal_ba_approve_url_from_text(&response.body) { - return Ok(json!({ "_ba_approve_url": url, "_raw_status": response.status })); - } - json_response(response, "stripe inline confirm") -} - -async fn stripe_confirm( - transport: &mut T, - base: &EndpointBase, - checkout: &Checkout, - init: &InitPayload, - stripe_pk: &str, - payment_method_id: &str, - stripe_hosted_url: &str, - provider_proxy: &str, -) -> Result { - let mut form = BTreeMap::new(); - form.insert("eid".to_string(), "NA".to_string()); - form.insert("payment_method".to_string(), payment_method_id.to_string()); - form.insert( - "expected_amount".to_string(), - expected_amount(&init.payload), - ); - form.insert( - "expected_payment_method_type".to_string(), - "ideal".to_string(), - ); - form.insert( - "return_url".to_string(), - stripe_confirm_return_url( - &checkout.cs_id, - &checkout.processor_entity, - stripe_hosted_url, - ), - ); - form.insert( - "_stripe_version".to_string(), - STRIPE_VERSION_FULL.to_string(), - ); - form.insert("guid".to_string(), stripe_browser_id()); - form.insert("muid".to_string(), stripe_browser_id()); - form.insert("sid".to_string(), stripe_browser_id()); - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert("version".to_string(), "6f8494a281".to_string()); - form.insert( - "init_checksum".to_string(), - first_string(&init.payload, &["init_checksum"]).unwrap_or_default(), - ); - form.insert( - "client_attribution_metadata[client_session_id]".to_string(), - Uuid::new_v4().to_string(), - ); - form.insert( - "client_attribution_metadata[checkout_session_id]".to_string(), - checkout.cs_id.clone(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_source]".to_string(), - "checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[merchant_integration_version]".to_string(), - "custom_checkout".to_string(), - ); - form.insert( - "client_attribution_metadata[payment_method_selection_flow]".to_string(), - "automatic".to_string(), - ); - form.insert( - "client_attribution_metadata[checkout_config_id]".to_string(), - first_string(&init.payload, &["config_id"]).unwrap_or_default(), - ); - form.insert("link_brand".to_string(), "link".to_string()); - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{}/confirm", checkout.cs_id)), - headers: stripe_headers(), - body: RequestBody::Form(form), - stage_proxy: "provider:NL".to_string(), - proxy_url: provider_proxy.to_string(), - }) - .await?; - json_response(response, "stripe confirm") -} - -struct ApproveRedirectPoll<'a> { - stripe_pk: &'a str, - poll_proxy: &'a str, - stage_region: &'a str, -} - -struct ApproveWithRetriesResult { - stripe_redirect_url: Option, -} - -async fn approve_with_retries( - transport: &mut T, - base: &EndpointBase, - headers: &BTreeMap, - checkout: &Checkout, - approve_proxy: &str, - link_type: LinkType, - redirect_poll: Option>, - steps: &mut Vec, - progress: Option<&ProgressSink>, -) -> Result { - let config = config_for_link_type(link_type); - add_step_with_progress( - steps, - "approve retry policy", - "ok", - &format!( - "total_attempts={}; concurrency={}", - config.approve_max_attempts, config.approve_concurrency - ), - progress, - ); - let header_token = access_token_from_headers(headers); - let base_approve_proxy = approve_proxy.to_string(); - let ping_headers = target_headers( - headers, - "/backend-api/sentinel/ping", - "https://chatgpt.com/", - ); - let _ = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.chatgpt("/backend-api/sentinel/ping"), - headers: ping_headers, - body: RequestBody::Json(json!({})), - stage_proxy: format!("approve:{}", config.approve_proxy_region), - proxy_url: base_approve_proxy.clone(), - }) - .await; - - let approve_body = json!({ "checkout_session_id": checkout.cs_id, "processor_entity": checkout.processor_entity }); - let referer = format!( - "https://chatgpt.com/checkout/{}/{}", - checkout.processor_entity, checkout.cs_id - ); - let approve_headers = - target_headers(headers, "/backend-api/payments/checkout/approve", &referer); - let mut last_error = None; - for attempt in 1..=config.approve_max_attempts { - let current_approve_proxy = if attempt == 1 { - base_approve_proxy.clone() - } else { - proxy_with_fresh_sid(&base_approve_proxy) - }; - if attempt > 1 { - add_step_with_progress( - steps, - "approve retry", - "info", - &format!( - "attempt {attempt}/{}; approve={}; retry proxy", - config.approve_max_attempts, - config.approve_proxy_region - ), - progress, - ); - } - let response = transport - .send(HttpRequest { - method: "POST".to_string(), - url: base.chatgpt("/backend-api/payments/checkout/approve"), - headers: approve_headers.clone(), - body: RequestBody::Json(approve_body.clone()), - stage_proxy: format!("approve:{}", config.approve_proxy_region), - proxy_url: current_approve_proxy.clone(), - }) - .await; - match response.and_then(|response| json_response(response, "chatgpt approve")) { - Ok(payload) - if first_string(&payload, &["result", "status", "state"]).as_deref() - == Some("approved") => - { - add_step_with_progress( - steps, - "approve", - "ok", - &format!("attempt {attempt}/20 approved"), - progress, - ); - if link_type == LinkType::Paypal { - if let Some(token) = header_token.as_deref() { - remember_approved_proxy( - token, - link_type, - config.approve_proxy_region, - ¤t_approve_proxy, - ); - add_step_with_progress( - steps, - "approved proxy cache", - "ok", - &format!( - "saved approved proxy: {}", - proxy_summary(¤t_approve_proxy) - ), - progress, - ); - } - } - if let Some(poll) = redirect_poll.as_ref() { - match poll_stripe_redirect( - transport, - base, - &checkout.cs_id, - poll.stripe_pk, - poll.poll_proxy, - link_type, - poll.stage_region, - APPROVED_REDIRECT_POLL_ATTEMPTS, - steps, - progress, - ) - .await - { - Ok(stripe_redirect_url) => { - return Ok(ApproveWithRetriesResult { - stripe_redirect_url: Some(stripe_redirect_url), - }); - } - Err(error) => { - let detail = error.to_string(); - add_step_with_progress( - steps, - "rebuild retry", - "warn", - &format!("attempt {attempt}/{MAX_APPROVE_ATTEMPTS} approved but redirect not ready; rebuilding checkout from start: {detail}"), - progress, - ); - return Err(error); - } - } - } - return Ok(ApproveWithRetriesResult { - stripe_redirect_url: None, - }); - } - Ok(payload) => { - let error = ExtractError::BadResponse(format!( - "chatgpt approve unexpected result: {payload}" - )); - if attempt >= MAX_APPROVE_ATTEMPTS || !retryable_chatgpt_approve_error(&error) { - return Err(error); - } - let retry_reason = if is_chatgpt_approve_blocked_error(&error) { - "blocked response" - } else { - "transient response" - }; - add_step_with_progress( - steps, - "approve retry", - "warn", - &format!("attempt {attempt}/{MAX_APPROVE_ATTEMPTS} {retry_reason}; retrying same checkout"), - progress, - ); - last_error = Some(error); - } - Err(error) => { - if attempt >= MAX_APPROVE_ATTEMPTS || !retryable_chatgpt_approve_error(&error) { - return Err(error); - } - let retry_reason = if is_chatgpt_approve_blocked_error(&error) { - "blocked/network response" - } else { - "network/transient error" - }; - add_step_with_progress( - steps, - "approve retry", - "warn", - &format!("attempt {attempt}/{MAX_APPROVE_ATTEMPTS} {retry_reason}; retrying same checkout: {error}"), - progress, - ); - last_error = Some(error); - } - } - } - Err(last_error - .unwrap_or_else(|| ExtractError::BadResponse("approve failed after retries".to_string()))) -} - -async fn poll_stripe_redirect( - transport: &mut T, - base: &EndpointBase, - cs_id: &str, - stripe_pk: &str, - poll_proxy: &str, - link_type: LinkType, - stage_region: &str, - attempts: usize, - steps: &mut Vec, - progress: Option<&ProgressSink>, -) -> Result { - let mut form = BTreeMap::new(); - form.insert( - "elements_session_client[client_betas][0]".to_string(), - "custom_checkout_server_updates_1".to_string(), - ); - form.insert( - "elements_session_client[client_betas][1]".to_string(), - "custom_checkout_manual_approval_1".to_string(), - ); - form.insert( - "elements_session_client[elements_init_source]".to_string(), - "custom_checkout".to_string(), - ); - form.insert( - "elements_session_client[referrer_host]".to_string(), - "chatgpt.com".to_string(), - ); - form.insert( - "elements_session_client[session_id]".to_string(), - format!( - "elements_session_{}", - &Uuid::new_v4().simple().to_string()[..11] - ), - ); - form.insert( - "elements_session_client[stripe_js_id]".to_string(), - Uuid::new_v4().to_string(), - ); - let elements_locale = match link_type { - LinkType::Ideal => ELEMENTS_LOCALE, - LinkType::Paypal => PAYPAL_ELEMENTS_LOCALE, - }; - form.insert( - "elements_session_client[locale]".to_string(), - elements_locale.to_string(), - ); - form.insert( - "elements_session_client[is_aggregation_expected]".to_string(), - "false".to_string(), - ); - form.insert( - "elements_options_client[saved_payment_method][enable_save]".to_string(), - "never".to_string(), - ); - form.insert( - "elements_options_client[saved_payment_method][enable_redisplay]".to_string(), - "never".to_string(), - ); - form.insert("key".to_string(), stripe_pk.to_string()); - form.insert( - "_stripe_version".to_string(), - STRIPE_VERSION_FULL.to_string(), - ); - let attempts = attempts.max(1); - let mut last_summary = String::new(); - for attempt in 1..=attempts { - let response = transport - .send(HttpRequest { - method: "GET".to_string(), - url: base.stripe(&format!("/v1/payment_pages/{cs_id}")), - headers: stripe_headers_for(link_type), - body: RequestBody::Form(form.clone()), - stage_proxy: format!("provider:{stage_region}"), - proxy_url: poll_proxy.to_string(), - }) - .await?; - let payload = json_response(response, "stripe payment_pages poll")?; - if link_type == LinkType::Paypal { - if let Some(summary) = setup_intent_last_error_summary(&payload) { - return Err(ExtractError::BadResponse(format!( - "stripe payment_pages poll: setup_intent.last_setup_error: {summary}" - ))); - } - } - if let Some(url) = extract_redirect_to_url(&payload) { - return Ok(url); - } - last_summary = payment_page_poll_summary(&payload); - if attempt < attempts { - add_step_with_progress( - steps, - "stripe redirect retry", - "info", - &format!( - "attempt {attempt}/{attempts}; redirect not ready ({last_summary}); retrying poll" - ), - progress, - ); - tokio::time::sleep(Duration::from_secs(1)).await; - } - } - Err(ExtractError::BadResponse(format!( - "redirect url resolution timeout after {attempts} poll(s): {last_summary}" - ))) -} - -async fn resolve_external_redirect( - transport: &mut T, - base: &EndpointBase, - redirect_url: &str, - provider_proxy: &str, - link_type: LinkType, -) -> Result { - let config = config_for_link_type(link_type); - let mut current = redirect_url.trim().to_string(); - for _ in 0..5 { - if current.is_empty() { - break; - } - if is_final_provider_url(¤t, link_type) { - return Ok(current); - } - let request_url = base.redirect(¤t); - let response = transport - .send(HttpRequest { - method: "GET".to_string(), - url: request_url, - headers: stripe_headers_for(link_type), - body: RequestBody::Empty, - stage_proxy: format!("provider:{}", config.provider_proxy_region), - proxy_url: provider_proxy.to_string(), - }) - .await?; - if let Some(url) = extract_provider_url_from_text(&response.body, link_type) { - return Ok(url); - } - if matches!(response.status, 301 | 302 | 303 | 307 | 308) { - if let Some(location) = response.headers.get("location").cloned() { - current = Url::parse(¤t) - .ok() - .and_then(|base| base.join(&location).ok()) - .map(|url| url.to_string()) - .unwrap_or(location); - if is_final_provider_url(¤t, link_type) { - return Ok(current); - } - continue; - } - } - break; - } - Err(ExtractError::BadResponse(format!( - "{} redirect not found; last_url={current}", - link_type.as_str() - ))) -} - -fn target_headers( - base: &BTreeMap, - path: &str, - referer: &str, -) -> BTreeMap { - let mut headers = base.clone(); - headers.insert("referer".to_string(), referer.to_string()); - headers.insert("x-openai-target-path".to_string(), path.to_string()); - headers.insert("x-openai-target-route".to_string(), path.to_string()); - headers -} - -fn access_token_from_headers(headers: &BTreeMap) -> Option { - headers - .get("authorization") - .or_else(|| headers.get("Authorization")) - .and_then(|value| normalize_access_token(value)) -} - -fn json_response(response: HttpResponse, label: &str) -> Result { - if response.status >= 400 { - let detail = upstream_error_summary(&response.body) - .map(|detail| format!(": {detail}")) - .unwrap_or_default(); - return Err(ExtractError::Http( - format!("{label} failed: HTTP {} from upstream", response.status) + &detail, - )); - } - serde_json::from_str(&response.body).map_err(|error| { - ExtractError::BadResponse(format!("{label} returned invalid JSON: {error}")) - }) -} - -fn upstream_error_summary(body: &str) -> Option { - let trimmed = body.trim(); - if trimmed.is_empty() { - return None; - } - if trimmed.starts_with('<') || trimmed.to_ascii_lowercase().contains("(trimmed) { - if let Some(summary) = json_error_summary(&payload) { - return Some(summary); - } - } - Some(short_error_text(trimmed, 240)) -} - -fn json_error_summary(payload: &Value) -> Option { - let error = payload.get("error").unwrap_or(payload); - let mut parts = Vec::new(); - for key in ["message", "code", "param", "type", "decline_code"] { - if let Some(value) = error.get(key).and_then(Value::as_str) { - let value = short_error_text(value, 180); - if !value.is_empty() { - parts.push(format!("{key}={value}")); - } - } - } - if parts.is_empty() { - for key in ["detail", "message", "error"] { - if let Some(value) = payload.get(key).and_then(Value::as_str) { - let value = short_error_text(value, 240); - if !value.is_empty() { - parts.push(format!("{key}={value}")); - break; - } - } - } - } - if parts.is_empty() { - None - } else { - Some(parts.join("; ")) - } -} - -fn short_error_text(text: &str, max_chars: usize) -> String { - let mut compact = text.split_whitespace().collect::>().join(" "); - if compact.chars().count() > max_chars { - compact = compact.chars().take(max_chars).collect::(); - compact.push_str("..."); - } - compact -} - -fn retryable_stripe_provider_error(error: &ExtractError) -> bool { - let text = error.to_string().to_ascii_lowercase(); - if !(text.contains("stripe confirm") - || text.contains("stripe payment_pages poll") - || text.contains("redirect url resolution timeout")) - { - return false; - } - [ - "http 400", - "invalid_request_error", - "checkout_upcoming_invoice_mismatch", - "setup_attempt_failed", - "requires_payment_method", - "payment_intent_unexpected_state", - "missing_redirect", - "redirect url resolution timeout", - "resource_missing", - "try again", - "temporarily", - "timeout", - ] - .iter() - .any(|needle| text.contains(needle)) -} - -fn redirect_poll_attempts_for_link_type(link_type: LinkType) -> usize { - match link_type { - LinkType::Ideal => IDEAL_REDIRECT_POLL_ATTEMPTS, - LinkType::Paypal => PAYPAL_REDIRECT_POLL_ATTEMPTS, - } -} - -fn retryable_paypal_provider_error(error: &ExtractError) -> bool { - let text = error.to_string().to_ascii_lowercase(); - [ - "stripe confirm failed", - "stripe payment_methods failed", - "stripe paypal tax region failed", - "stripe payment_pages poll", - "invalid_request_error", - "setup_attempt_failed", - "requires_payment_method", - "payment_intent_unexpected_state", - "checkout_upcoming_invoice_mismatch", - "missing_redirect", - "redirect url resolution failed", - "redirect url resolution timeout", - "paypal redirect not found", - "resource_missing", - "not_active", - "blocked", - "generic_decline", - ] - .iter() - .any(|needle| text.contains(needle)) -} - -fn setup_intent_last_error_summary(payload: &Value) -> Option { - let error = payload.pointer("/setup_intent/last_setup_error")?; - if error.is_null() { - return None; - } - let mut parts = Vec::new(); - for key in ["code", "decline_code", "type", "message"] { - if let Some(value) = error.get(key).and_then(Value::as_str) { - let value = short_error_text(value, 180); - if !value.is_empty() { - parts.push(format!("{key}={value}")); - } - } - } - if let Some(pm_id) = error - .pointer("/payment_method/id") - .and_then(Value::as_str) - .filter(|value| value.starts_with("pm_")) - { - parts.push(format!("payment_method={pm_id}")); - } - if let Some(country) = error - .pointer("/payment_method/billing_details/address/country") - .and_then(Value::as_str) - { - parts.push(format!("billing_country={country}")); - } - if let Some(country) = error - .pointer("/payment_method/paypal/country") - .and_then(Value::as_str) - .filter(|value| !value.trim().is_empty()) - { - parts.push(format!("paypal_country={country}")); - } - if parts.is_empty() { - Some(short_error_text(&error.to_string(), 240)) - } else { - Some(parts.join("; ")) - } -} - -fn payment_page_poll_summary(payload: &Value) -> String { - let object = match payload.as_object() { - Some(object) => object, - None => return short_error_text(&payload.to_string(), 180), - }; - let keys = object - .keys() - .take(8) - .map(String::as_str) - .collect::>() - .join(","); - let state = payload - .get("state") - .and_then(Value::as_str) - .or_else(|| { - payload - .get("submission_attempt") - .and_then(|value| value.get("state")) - .and_then(Value::as_str) - }) - .unwrap_or("-"); - let status = payload - .get("status") - .and_then(Value::as_str) - .or_else(|| { - payload - .get("setup_intent") - .and_then(|value| value.get("status")) - .and_then(Value::as_str) - }) - .unwrap_or("-"); - format!("keys=[{keys}]; state={state}; status={status}") -} - -fn is_chatgpt_approve_blocked_error(error: &ExtractError) -> bool { - let text = error.to_string().to_ascii_lowercase(); - text.contains("chatgpt approve") - && [ - "blocked", - "country", - "region", - "unsupported", - "unavailable", - "forbidden", - "403", - ] - .iter() - .any(|needle| text.contains(needle)) -} - -fn retryable_chatgpt_approve_error(error: &ExtractError) -> bool { - let text = error.to_string().to_ascii_lowercase(); - is_chatgpt_approve_blocked_error(error) - || retryable_transient_error(error) - || (text.contains("chatgpt approve") && text.contains("exception")) -} - -fn is_amount_policy_error(error: &ExtractError) -> bool { - error - .to_string() - .to_ascii_lowercase() - .contains("amount policy failed") -} - -fn retryable_transient_error(error: &ExtractError) -> bool { - let text = error.to_string().to_ascii_lowercase(); - if text.contains("amount policy failed") || text.contains("access token") { - return false; - } - [ - "429", - "500", - "502", - "503", - "504", - "bad gateway", - "gateway timeout", - "request failed", - "error sending request", - "tls", - "ssl", - "timeout", - "timed out", - "connection", - "connect", - "dns", - "getaddrinfo", - "eof", - "proxy error", - "remote disconnected", - "reset", - "temporarily", - "try again", - "redirect url resolution failed", - "ideal redirect not found", - "checkout response missing cs_id", - "stripe init response missing", - "invalid json", - ] - .iter() - .any(|needle| text.contains(needle)) -} - -fn first_string(value: &Value, keys: &[&str]) -> Option { - let object = value.as_object()?; - keys.iter().find_map(|key| { - object - .get(*key) - .and_then(Value::as_str) - .map(ToOwned::to_owned) - }) -} - -fn expected_amount(payload: &Value) -> String { - if let Some(due) = payload - .pointer("/total_summary/due") - .and_then(number_or_string) - { - return due; - } - if let Some(due) = payload - .pointer("/invoice/amount_due") - .and_then(number_or_string) - { - return due; - } - if let Some(items) = payload.get("line_items").and_then(Value::as_array) { - let mut total = 0_i64; - let mut found = false; - for item in items { - if let Some(amount) = item.get("amount").and_then(Value::as_i64) { - total += amount; - found = true; - } - } - if found { - return total.to_string(); - } - } - "0".to_string() -} - -fn number_or_string(value: &Value) -> Option { - value - .as_i64() - .map(|value| value.to_string()) - .or_else(|| value.as_str().map(ToOwned::to_owned)) -} - -fn display_amount(amount: &str) -> String { - display_amount_for(amount, "EUR") -} - -fn display_amount_for(amount: &str, currency: &str) -> String { - match amount.parse::() { - Ok(value) => { - let symbol = match currency { - "EUR" => "€", - "USD" => "$", - _ => "", - }; - if symbol.is_empty() { - format!("{:.2} {currency}", value as f64 / 100.0) - } else { - format!("{symbol}{:.2}", value as f64 / 100.0) - } - } - Err(_) => format!("{amount} {currency}"), - } -} - -fn paypal_provider_failed( - error: ExtractError, - checkout: &Checkout, - init: &InitPayload, - amount: &str, - payment_method_id: &str, -) -> ExtractError { - ExtractError::PaypalProviderFailed { - detail: error.to_string(), - cs_id: checkout.cs_id.clone(), - processor_entity: checkout.processor_entity.clone(), - stripe_hosted_url: init.stripe_hosted_url.clone(), - amount: amount.to_string(), - payment_method_id: payment_method_id.to_string(), - } -} - -fn paypal_fallback_from_error(error: &ExtractError) -> Option { - match error { - ExtractError::PaypalProviderFailed { - cs_id, - processor_entity, - stripe_hosted_url, - amount, - payment_method_id, - .. - } => Some(PaypalFallback { - cs_id: cs_id.clone(), - processor_entity: processor_entity.clone(), - stripe_hosted_url: stripe_hosted_url.clone(), - amount: amount.clone(), - payment_method_id: payment_method_id.clone(), - }), - _ => None, - } -} - -fn paypal_fallback_output( - fallback: PaypalFallback, - steps: &[Step], - provider_error: String, -) -> ExtractOutput { - let hosted_long_url = to_openai_pay_url(&fallback.stripe_hosted_url) - .unwrap_or_else(|| stripe_checkout_long_url(&fallback.cs_id, &fallback.processor_entity)); - ExtractOutput { - ok: true, - cs_id: fallback.cs_id, - billing_country: "US".to_string(), - currency: "USD".to_string(), - payment_method_id: fallback.payment_method_id, - stripe_redirect_url: hosted_long_url.clone(), - provider_redirect_url: String::new(), - long_url: hosted_long_url, - amount: fallback.amount.clone(), - amount_display: display_amount_for(&fallback.amount, "USD"), - fallback: true, - provider_error, - config: config_for_link_type(LinkType::Paypal), - steps: steps.to_vec(), - } -} - -fn paypal_billing_country() -> &'static str { - PAYPAL_BILLING_COUNTRY -} - -fn paypal_billing_state(country: &str) -> Option<&'static str> { - match country.trim().to_ascii_uppercase().as_str() { - "US" => Some(PAYPAL_BILLING_STATE), - _ => None, - } -} - -fn paypal_billing_form( - prefix: &str, - email: &str, - _billing_country: &str, -) -> BTreeMap { - let mut form = BTreeMap::new(); - let (name, country, line1, city, state, postal_code) = ( - "John Doe", - PAYPAL_BILLING_COUNTRY, - "3110 Sunset Boulevard", - "Los Angeles", - PAYPAL_BILLING_STATE, - "90026", - ); - form.insert(format!("{prefix}[name]"), name.to_string()); - form.insert(format!("{prefix}[email]"), email.to_string()); - form.insert(format!("{prefix}[address][country]"), country.to_string()); - form.insert(format!("{prefix}[address][line1]"), line1.to_string()); - form.insert(format!("{prefix}[address][city]"), city.to_string()); - form.insert( - format!("{prefix}[address][postal_code]"), - postal_code.to_string(), - ); - form.insert(format!("{prefix}[address][state]"), state.to_string()); - form -} - -fn stripe_browser_id() -> String { - format!( - "{}{}", - Uuid::new_v4(), - &Uuid::new_v4().simple().to_string()[..8] - ) -} - -fn stripe_context(init_payload: &Value, link_type: LinkType) -> StripeContext { - let paypal_mode = link_type == LinkType::Paypal; - let config_id = first_string(init_payload, &["config_id"]).unwrap_or_default(); - let init_checksum = first_string(init_payload, &["init_checksum"]).unwrap_or_default(); - StripeContext { - stripe_js_id: Uuid::new_v4().to_string(), - client_session_id: Uuid::new_v4().to_string(), - guid: stripe_browser_id(), - muid: stripe_browser_id(), - sid: stripe_browser_id(), - elements_session_id: format!( - "elements_session_{}", - &Uuid::new_v4().simple().to_string()[..11] - ), - elements_session_config_id: if config_id.is_empty() { - Uuid::new_v4().to_string() - } else { - config_id.clone() - }, - config_id, - init_checksum, - checkout_amount: expected_amount(init_payload), - locale: if paypal_mode { - PAYPAL_ELEMENTS_LOCALE.to_string() - } else { - ELEMENTS_LOCALE.to_string() - }, - runtime_version: if paypal_mode { - PAYPAL_STRIPE_RUNTIME_VERSION.to_string() - } else { - DEFAULT_STRIPE_RUNTIME_VERSION.to_string() - }, - stripe_version: if paypal_mode { - PAYPAL_STRIPE_VERSION.to_string() - } else { - STRIPE_VERSION_FULL.to_string() - }, - } -} - -fn apply_stripe_fingerprint(form: &mut BTreeMap, link_type: LinkType) -> bool { - let Some(fingerprint) = stripe_fingerprint_for_link_type(link_type) else { - return false; - }; - for (key, value) in fingerprint { - form.insert(key, value); - } - true -} - -fn stripe_fingerprint_for_link_type(link_type: LinkType) -> Option> { - let capture = stripe_fingerprint_capture(link_type)?; - let mut parsed = BTreeMap::new(); - for (key, value) in url::form_urlencoded::parse(capture.as_bytes()) { - parsed.insert(key.into_owned(), value.into_owned()); - } - let keys = ["js_checksum", "rv_timestamp", "version", "_stripe_version"]; - let mut fingerprint = BTreeMap::new(); - for key in keys { - let value = parsed.get(key)?.trim(); - if value.is_empty() { - return None; - } - fingerprint.insert(key.to_string(), value.to_string()); - } - Some(fingerprint) -} - -fn stripe_fingerprint_capture(link_type: LinkType) -> Option { - for path in stripe_fingerprint_capture_paths(link_type) { - if let Ok(text) = fs::read_to_string(&path) { - if !text.trim().is_empty() { - return Some(text); - } - } - } - None -} - -fn stripe_fingerprint_capture_paths(link_type: LinkType) -> Vec { - let names: &[&str] = match link_type { - LinkType::Paypal => &[ - "paypal_confirm_post.txt", - "paypal_fresh_confirm_post_2.txt", - "paypal_sweep_confirm_post.txt", - ], - LinkType::Ideal => &[], - }; - let mut paths = Vec::new(); - for name in names { - paths.push(FsPath::new(FINGERPRINT_DATA_DIR).join(name)); - paths.push(FsPath::new(FINGERPRINT_LEGACY_DIR).join(name)); - } - paths -} - -fn to_openai_pay_url(stripe_hosted_url: &str) -> Option { - let raw = stripe_hosted_url.trim(); - if raw.is_empty() { - return None; - } - if let Some(rest) = raw.strip_prefix("https://checkout.stripe.com") { - return Some(format!("https://pay.openai.com{rest}")); - } - match Url::parse(raw) { - Ok(mut parsed) if parsed.host_str() == Some("checkout.stripe.com") => { - parsed.set_host(Some("pay.openai.com")).ok()?; - Some(parsed.to_string()) - } - Ok(_) => Some(raw.to_string()), - Err(_) => None, - } -} - -fn chatgpt_success_return_url(cs_id: &str, processor_entity: &str) -> String { - format!( - "https://chatgpt.com/checkout/verify?stripe_session_id={cs_id}&processor_entity={processor_entity}&plan_type=plus" - ) -} - -fn stripe_checkout_long_url(cs_id: &str, processor_entity: &str) -> String { - let success = chatgpt_success_return_url(cs_id, processor_entity); - format!( - "https://checkout.stripe.com/c/pay/{cs_id}?returned_from_redirect=true&ui_mode=custom&return_url={}", - url::form_urlencoded::byte_serialize(success.as_bytes()).collect::() - ) -} - -fn stripe_confirm_return_url( - cs_id: &str, - processor_entity: &str, - stripe_hosted_url: &str, -) -> String { - let hosted_url = to_openai_pay_url(stripe_hosted_url) - .unwrap_or_else(|| stripe_checkout_long_url(cs_id, processor_entity)); - let Ok(mut parsed) = Url::parse(&hosted_url) else { - return hosted_url; - }; - let host = parsed.host_str().unwrap_or_default(); - if host != "pay.openai.com" && host != "checkout.stripe.com" { - return hosted_url; - } - let mut pairs = parsed - .query_pairs() - .map(|(key, value)| (key.to_string(), value.to_string())) - .collect::>(); - if !pairs.iter().any(|(key, _)| key == "success_return_url") { - pairs.push(( - "success_return_url".to_string(), - chatgpt_success_return_url(cs_id, processor_entity), - )); - let mut serializer = url::form_urlencoded::Serializer::new(String::new()); - for (key, value) in &pairs { - serializer.append_pair(key, value); - } - parsed.set_query(Some(&serializer.finish())); - } - parsed.to_string() -} - -fn paypal_confirm_return_url( - cs_id: &str, - processor_entity: &str, - stripe_hosted_url: &str, -) -> String { - let hosted_url = to_openai_pay_url(stripe_hosted_url) - .unwrap_or_else(|| stripe_checkout_long_url(cs_id, processor_entity)); - let Ok(mut parsed) = Url::parse(&hosted_url) else { - return hosted_url; - }; - let mut pairs = parsed - .query_pairs() - .filter(|(key, _)| !matches!(key.as_ref(), "redirect_pm_type" | "lid" | "ui_mode")) - .map(|(key, value)| (key.to_string(), value.to_string())) - .collect::>(); - pairs.push(("redirect_pm_type".to_string(), "paypal".to_string())); - pairs.push(("lid".to_string(), Uuid::new_v4().to_string())); - pairs.push(("ui_mode".to_string(), "custom".to_string())); - let mut serializer = url::form_urlencoded::Serializer::new(String::new()); - for (key, value) in &pairs { - serializer.append_pair(key, value); - } - parsed.set_query(Some(&serializer.finish())); - parsed.to_string() -} - -fn confirm_requires_approval(payload: &Value) -> bool { - payload - .pointer("/submission_attempt/state") - .and_then(Value::as_str) - == Some("requires_approval") -} - -fn find_nested_payment_method_id(payload: &Value) -> Option { - match payload { - Value::Object(map) => { - if let Some(pm_id) = map - .get("payment_method") - .and_then(Value::as_str) - .filter(|value| value.starts_with("pm_")) - { - return Some(pm_id.to_string()); - } - if let Some(pm_id) = map - .get("payment_method") - .and_then(|value| value.get("id")) - .and_then(Value::as_str) - .filter(|value| value.starts_with("pm_")) - { - return Some(pm_id.to_string()); - } - if map.get("object").and_then(Value::as_str) == Some("payment_method") { - if let Some(pm_id) = map - .get("id") - .and_then(Value::as_str) - .filter(|value| value.starts_with("pm_")) - { - return Some(pm_id.to_string()); - } - } - for key in [ - "setup_intent", - "payment_intent", - "last_setup_error", - "payment_method", - "data", - ] { - if let Some(pm_id) = map.get(key).and_then(find_nested_payment_method_id) { - return Some(pm_id); - } - } - map.values().find_map(find_nested_payment_method_id) - } - Value::Array(items) => items.iter().find_map(find_nested_payment_method_id), - _ => None, - } -} - -fn extract_redirect_to_url(payload: &Value) -> Option { - if let Some(url) = find_paypal_ba_approve_url(payload) { - return Some(url); - } - if let Some(url) = find_ideal_url(payload) { - return Some(url); - } - if let Some(url) = payload - .pointer("/next_action/redirect_to_url/url") - .and_then(Value::as_str) - .filter(|url| is_payment_redirect_url(url)) - { - return Some(url.to_string()); - } - match payload { - Value::String(text) if is_payment_redirect_url(text) => Some(text.to_string()), - Value::Array(items) => items.iter().find_map(extract_redirect_to_url), - Value::Object(map) => { - for key in ["url", "redirect_url", "hosted_url"] { - if let Some(url) = map - .get(key) - .and_then(Value::as_str) - .filter(|url| is_payment_redirect_url(url)) - { - return Some(url.to_string()); - } - } - map.iter() - .filter(|(key, _)| key.as_str() != "return_url") - .find_map(|(_, value)| extract_redirect_to_url(value)) - } - _ => None, - } -} - -fn find_paypal_ba_approve_url(value: &Value) -> Option { - match value { - Value::String(text) => extract_paypal_ba_approve_url_from_text(text), - Value::Array(items) => items.iter().find_map(find_paypal_ba_approve_url), - Value::Object(map) => { - for (key, value) in map { - if let Some(url) = extract_paypal_ba_approve_url_from_text(key) { - return Some(url); - } - if let Some(url) = find_paypal_ba_approve_url(value) { - return Some(url); - } - } - None - } - _ => None, - } -} - -fn extract_paypal_ba_approve_url_from_text(text: &str) -> Option { - let mut normalized = text - .replace("\\/", "/") - .replace("\\u0026", "&") - .replace("\\u003d", "=") - .replace("\\u003D", "=") - .replace("&", "&"); - if normalized.contains('%') { - normalized = url::form_urlencoded::parse(normalized.as_bytes()) - .map(|(key, value)| { - if value.is_empty() { - key.into_owned() - } else { - format!("{key}={value}") - } - }) - .collect::>() - .join("&"); - } - static PAYPAL_BA_APPROVE_RE: OnceLock = OnceLock::new(); - let approve_re = PAYPAL_BA_APPROVE_RE.get_or_init(|| { - Regex::new(r#"(?i)(?:(?:https?:)?//)?(?:www\.)?paypal\.com/agreements/approve\?[^\s\"'<>]*?ba_token=(BA-[A-Za-z0-9_-]+)"#) - .expect("valid paypal approve regex") - }); - if let Some(token) = approve_re - .captures(&normalized) - .and_then(|captures| captures.get(1)) - .map(|matched| matched.as_str()) - { - return Some(paypal_ba_approve_url_from_token(token)); - } - static PAYPAL_BA_TOKEN_RE: OnceLock = OnceLock::new(); - let token_re = PAYPAL_BA_TOKEN_RE.get_or_init(|| { - Regex::new( - r#"(?i)(?:ba_token|baToken|billing_agreement_token|billingAgreementToken)[\s\"'=:]+(BA-[A-Za-z0-9_-]+)"#, - ) - .expect("valid paypal token regex") - }); - token_re - .captures(&normalized) - .and_then(|captures| captures.get(1)) - .map(|matched| paypal_ba_approve_url_from_token(matched.as_str())) -} - -fn paypal_ba_approve_url_from_token(token: &str) -> String { - let token = token.trim_matches(|ch: char| { - ch.is_whitespace() - || matches!( - ch, - '"' | '\'' | '<' | '>' | ')' | ',' | '.' | ';' | ']' | '}' - ) - }); - format!( - "https://www.paypal.com/agreements/approve?ba_token={}", - url::form_urlencoded::byte_serialize(token.as_bytes()).collect::() - ) -} - -fn find_ideal_url(value: &Value) -> Option { - match value { - Value::String(text) => extract_ideal_url_from_text(text), - Value::Array(items) => items.iter().find_map(find_ideal_url), - Value::Object(map) => map.values().find_map(find_ideal_url), - _ => None, - } -} - -fn extract_ideal_url_from_text(text: &str) -> Option { - static IDEAL_URL_RE: OnceLock = OnceLock::new(); - let ideal_url_re = IDEAL_URL_RE.get_or_init(|| { - Regex::new(r#"https://pay\.ideal\.nl/transactions/[^\s\"'<>]+"#) - .expect("valid ideal url regex") - }); - ideal_url_re - .find(text) - .map(|matched| matched.as_str().to_string()) - .filter(|url| is_ideal_payment_url(url)) -} - -fn is_ideal_payment_url(url: &str) -> bool { - Url::parse(url) - .ok() - .map(|parsed| { - parsed.host_str() == Some("pay.ideal.nl") && parsed.path().starts_with("/transactions/") - }) - .unwrap_or(false) -} - -fn is_paypal_ba_approve_url(url: &str) -> bool { - Url::parse(url) - .ok() - .map(|parsed| { - let host = parsed.host_str().unwrap_or_default(); - let path = parsed.path().trim_end_matches('/'); - (host.eq_ignore_ascii_case("paypal.com") - || host.to_ascii_lowercase().ends_with(".paypal.com")) - && path.eq_ignore_ascii_case("/agreements/approve") - && parsed - .query_pairs() - .any(|(key, value)| key == "ba_token" && !value.trim().is_empty()) - }) - .unwrap_or(false) -} - -fn is_final_provider_url(url: &str, link_type: LinkType) -> bool { - match link_type { - LinkType::Ideal => is_ideal_payment_url(url), - LinkType::Paypal => is_paypal_ba_approve_url(url), - } -} - -fn extract_provider_url_from_text(text: &str, link_type: LinkType) -> Option { - match link_type { - LinkType::Ideal => extract_ideal_url_from_text(text), - LinkType::Paypal => extract_paypal_ba_approve_url_from_text(text), - } -} - -fn is_payment_redirect_url(url: &str) -> bool { - if is_ideal_payment_url(url) || is_paypal_ba_approve_url(url) { - return true; - } - Url::parse(url) - .ok() - .map(|parsed| { - let host = parsed.host_str().unwrap_or_default(); - let path = parsed.path(); - (host.eq_ignore_ascii_case("pm-redirects.stripe.com") - && path.starts_with("/authorize/")) - || (host.eq_ignore_ascii_case("hooks.stripe.com") && path.starts_with("/redirect/")) - }) - .unwrap_or(false) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[derive(Default)] - struct FakeTransport { - requests: Vec, - init_calls: usize, - } - - #[async_trait] - impl Transport for FakeTransport { - async fn send(&mut self, request: HttpRequest) -> Result { - self.requests.push(request.clone()); - let path = if request.url == "https://pm-redirects.stripe.com/authorize/test" { - "/authorize/test".to_string() - } else { - Url::parse(&request.url) - .map(|url| url.path().to_string()) - .unwrap_or_else(|_| request.url.clone()) - }; - let body = match path.as_str() { - "/backend-api/payments/checkout" => serde_json::json!({ - "checkout_session_id": "cs_test_123", - "processor_entity": "openai_ie", - "publishable_key": "pk_REDACTED" - }), - "/v1/payment_pages/cs_test_123/init" => { - self.init_calls += 1; - serde_json::json!({ - "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_test_123#fidkdWxOYHwnPyd1blpxYHZxWjA0S2g", - "init_checksum": format!("checksum_{}", self.init_calls), - "total_summary": { "due": if self.init_calls == 1 { 2300 } else { 0 } }, - "payment_method_types": ["card", "ideal", "apple_pay"], - "currency": "eur", - "config_id": "cfg_123" - }) - } - "/backend-api/payments/checkout/update" => serde_json::json!({ "success": true }), - "/backend-api/payments/checkout/taxes" => { - serde_json::json!({ "using_automatic_tax": true }) - } - "/v1/payment_methods" => serde_json::json!({ "id": "pm_test_ideal" }), - "/v1/payment_pages/cs_test_123/confirm" => serde_json::json!({ - "submission_attempt": { "state": "requires_approval" } - }), - "/backend-api/sentinel/ping" => serde_json::json!({ "status": "OK" }), - "/backend-api/payments/checkout/approve" => { - serde_json::json!({ "result": "approved" }) - } - "/v1/payment_pages/cs_test_123" if request.method == "POST" => { - serde_json::json!({}) - } - "/v1/payment_pages/cs_test_123" => serde_json::json!({ - "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://pm-redirects.stripe.com/authorize/test" } } - }), - "/authorize/test" => serde_json::json!({}), - other => panic!("unexpected request path {other}"), - }; - let mut headers = BTreeMap::new(); - if path == "/authorize/test" { - headers.insert( - "location".to_string(), - "https://pay.ideal.nl/transactions/test".to_string(), - ); - return Ok(HttpResponse { - status: 302, - headers, - body: String::new(), - }); - } - Ok(HttpResponse { - status: 200, - headers, - body: body.to_string(), - }) - } - } - - #[tokio::test] - async fn happy_path_extracts_ideal_link_with_locked_config() { - let mut transport = FakeTransport::default(); - let output = extract_ideal_link( - &mut transport, - ExtractInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - proxy: "http://user-region-US-sid-old-t-1:pass@proxy.example:3010".to_string(), - checkout_proxy_pool: Vec::new(), - promotion_proxy_pool: Vec::new(), - paypal_provider_proxy_pool: Vec::new(), - base_url: "http://IP_REDACTED:8792".to_string(), - link_type: "ideal".to_string(), - }, - ) - .await - .expect("happy path should succeed"); - - assert!(output.ok, "extractor should report ok=true"); - assert_eq!(output.long_url, "https://pay.ideal.nl/transactions/test"); - assert_eq!(output.cs_id, "cs_test_123"); - assert_eq!(output.billing_country, "NL"); - assert_eq!(output.currency, "EUR"); - assert_eq!(output.payment_method_id, "pm_test_ideal"); - assert_eq!(output.config, locked_config()); - - let checkout = &transport.requests[0]; - assert_eq!(checkout.stage_proxy, "checkout:NL"); - assert_eq!( - checkout.proxy_url, - "http://user-region-NL-sid-old-t-1:pass@proxy.example:3010" - ); - assert!( - matches!(&checkout.body, RequestBody::Json(body) if body["billing_details"]["country"] == "NL" && body["billing_details"]["currency"] == "EUR" && body["checkout_ui_mode"] == "custom") - ); - assert_eq!( - checkout.headers.get("user-agent").map(String::as_str), - Some(APPLE_SAFARI_USER_AGENT) - ); - - let promotion = transport - .requests - .iter() - .find(|request| { - request - .url - .ends_with("/backend-api/payments/checkout/update") - }) - .expect("VN checkout/update must be sent"); - assert_eq!(promotion.stage_proxy, "promotion:VN"); - assert_eq!( - promotion.proxy_url, - "http://user-region-VN-sid-old-t-1:pass@proxy.example:3010" - ); - assert!(matches!(&promotion.body, RequestBody::Json(body) - if body["plan_name"] == "chatgptplusplan" - && body["price_interval"] == "month" - && body["seat_quantity"] == 1 - && body["promo_campaign"]["promo_campaign_id"] == "plus-1-month-free")); - - let payment_method = transport - .requests - .iter() - .find(|request| request.url.ends_with("/v1/payment_methods")) - .expect("payment_methods request should be sent"); - assert_eq!(payment_method.stage_proxy, "provider:NL"); - assert_eq!( - payment_method.proxy_url, - "http://user-region-NL-sid-old-t-1:pass@proxy.example:3010" - ); - assert!( - matches!(&payment_method.body, RequestBody::Form(form) if form.get("type").map(String::as_str) == Some("ideal") && form.get("billing_details[address][country]").map(String::as_str) == Some("NL")) - ); - - let approve = transport - .requests - .iter() - .find(|request| { - request - .url - .ends_with("/backend-api/payments/checkout/approve") - }) - .expect("approve endpoint must be called"); - assert_eq!(approve.stage_proxy, "approve:NL"); - assert_eq!( - approve.proxy_url, - "http://user-region-NL-sid-old-t-1:pass@proxy.example:3010" - ); - assert!( - transport - .requests - .iter() - .all(|request| !request.url.contains("ipwho") - && !request.url.contains("ipify") - && !request.url.contains("myip")), - "new Rust flow must not call IP-check endpoints" - ); - } - - #[tokio::test] - async fn submitted_ideal_pools_route_promotion_only_through_promotion_proxy() { - let checkout_proxy = "http://checkout-user:pass@checkout.example:3010"; - let promotion_proxy = "http://promotion-user:pass@promotion.example:3020"; - let mut transport = FakeTransport::default(); - extract_ideal_link( - &mut transport, - ExtractInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - proxy: checkout_proxy.to_string(), - checkout_proxy_pool: vec![checkout_proxy.to_string()], - promotion_proxy_pool: vec![promotion_proxy.to_string()], - paypal_provider_proxy_pool: Vec::new(), - base_url: "http://IP_REDACTED:8792".to_string(), - link_type: "ideal".to_string(), - }, - ) - .await - .expect("submitted proxy pools should complete the fake iDEAL flow"); - - for request in &transport.requests { - if request - .url - .ends_with("/backend-api/payments/checkout/update") - { - assert_eq!(request.proxy_url, promotion_proxy); - } else { - assert_eq!( - request.proxy_url, checkout_proxy, - "non-promotion request unexpectedly changed proxy: {}", - request.url - ); - } - } - } - - #[test] - fn submitted_ideal_pools_rotate_independently_by_rebuild_attempt() { - let input = ExtractInput { - access_token: "at_test".to_string(), - proxy: "http://checkout-one.example:3010".to_string(), - checkout_proxy_pool: vec![ - "http://checkout-one.example:3010".to_string(), - "http://checkout-two.example:3010".to_string(), - ], - promotion_proxy_pool: vec![ - "http://promotion-one.example:3020".to_string(), - "http://promotion-two.example:3020".to_string(), - "http://promotion-three.example:3020".to_string(), - ], - paypal_provider_proxy_pool: Vec::new(), - base_url: String::new(), - link_type: "ideal".to_string(), - }; - - let attempt_four = ideal_proxies_for_attempt(&input, 4) - .expect("both submitted pools should be selectable"); - assert_eq!(attempt_four.0, "http://checkout-two.example:3010"); - assert_eq!(attempt_four.1, "http://promotion-one.example:3020"); - assert_eq!((attempt_four.2, attempt_four.3), (2, 1)); - } - - #[test] - fn submitted_paypal_pools_rotate_independently_by_rebuild_attempt() { - let input = ExtractInput { - access_token: "at_test".to_string(), - proxy: "http://checkout-one.example:3010".to_string(), - checkout_proxy_pool: vec![ - "http://checkout-one.example:3010".to_string(), - "http://checkout-two.example:3010".to_string(), - ], - promotion_proxy_pool: vec![ - "http://promotion-one.example:3020".to_string(), - "http://promotion-two.example:3020".to_string(), - "http://promotion-three.example:3020".to_string(), - ], - paypal_provider_proxy_pool: vec![ - "http://provider-one.example:3030".to_string(), - "http://provider-two.example:3030".to_string(), - "http://provider-three.example:3030".to_string(), - "http://provider-four.example:3030".to_string(), - ], - base_url: String::new(), - link_type: "paypal".to_string(), - }; - - let attempt_four = paypal_proxies_for_attempt(&input, 4) - .expect("all submitted PayPal pools should be selectable"); - assert_eq!(attempt_four.0, "http://checkout-two.example:3010"); - assert_eq!(attempt_four.1, "http://promotion-one.example:3020"); - assert_eq!(attempt_four.2, "http://provider-four.example:3030"); - assert_eq!((attempt_four.3, attempt_four.4, attempt_four.5), (2, 1, 4)); - } - - #[tokio::test] - async fn submitted_paypal_pools_route_us_vn_tr_us() { - #[derive(Default)] - struct PaypalTransport { - requests: Vec, - } - - #[async_trait] - impl Transport for PaypalTransport { - async fn send(&mut self, request: HttpRequest) -> Result { - self.requests.push(request.clone()); - let path = if request.url == "https://pm-redirects.stripe.com/authorize/paypal" { - "/authorize/paypal".to_string() - } else { - Url::parse(&request.url) - .map(|url| url.path().to_string()) - .unwrap_or_else(|_| request.url.clone()) - }; - let body = match path.as_str() { - "/backend-api/payments/checkout" => serde_json::json!({ - "checkout_session_id": "cs_paypal_pool_test", - "processor_entity": "openai_ie", - "publishable_key": "pk_REDACTED" - }), - "/backend-api/payments/checkout/update" => { - serde_json::json!({ "success": true }) - } - "/v1/payment_pages/cs_paypal_pool_test/init" => serde_json::json!({ - "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_paypal_pool_test", - "init_checksum": "checksum_paypal_pool_test", - "total_summary": { "due": 0 }, - "payment_method_types": ["paypal"], - "currency": "usd", - "config_id": "cfg_paypal_pool_test" - }), - "/v1/payment_methods" => serde_json::json!({ "id": "pm_paypal_pool_test" }), - "/v1/payment_pages/cs_paypal_pool_test/confirm" => serde_json::json!({ - "submission_attempt": { "state": "requires_approval" } - }), - "/backend-api/sentinel/ping" => serde_json::json!({ "status": "OK" }), - "/backend-api/payments/checkout/approve" => { - serde_json::json!({ "result": "approved" }) - } - "/v1/payment_pages/cs_paypal_pool_test" if request.method == "POST" => { - serde_json::json!({}) - } - "/v1/payment_pages/cs_paypal_pool_test" => serde_json::json!({ - "next_action": { - "type": "redirect_to_url", - "redirect_to_url": { - "url": "https://pm-redirects.stripe.com/authorize/paypal" - } - } - }), - "/authorize/paypal" => serde_json::json!({}), - other => panic!("unexpected PayPal request path {other}"), - }; - let mut headers = BTreeMap::new(); - if path == "/authorize/paypal" { - headers.insert( - "location".to_string(), - "https://www.paypal.com/agreements/approve?ba_token=BA-POOL-TEST" - .to_string(), - ); - return Ok(HttpResponse { - status: 302, - headers, - body: String::new(), - }); - } - Ok(HttpResponse { - status: 200, - headers, - body: body.to_string(), - }) - } - } - - let checkout_proxy = - "http://checkout-user-region-US-sid-checkout-t-1:pass@checkout.example:3010"; - let promotion_proxy = - "http://promotion-user-region-VN-sid-promotion-t-1:pass@promotion.example:3020"; - let provider_proxy = - "http://provider-user-region-TR-sid-provider-t-1:pass@provider.example:3030"; - let mut transport = PaypalTransport::default(); - let output = extract_paypal_link_with_progress( - &mut transport, - ExtractInput { - access_token: - "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6InBheXBhbC1wb29sQGV4YW1wbGUuY29tIn0.sig" - .to_string(), - proxy: checkout_proxy.to_string(), - checkout_proxy_pool: vec![checkout_proxy.to_string()], - promotion_proxy_pool: vec![promotion_proxy.to_string()], - paypal_provider_proxy_pool: vec![provider_proxy.to_string()], - base_url: "http://localhost:8792".to_string(), - link_type: "paypal".to_string(), - }, - None, - ) - .await - .expect("submitted PayPal pools should complete the fake flow"); - - assert_eq!( - output.long_url, - "https://www.paypal.com/agreements/approve?ba_token=BA-POOL-TEST" - ); - assert_eq!(output.billing_country, "US"); - assert_eq!(output.currency, "USD"); - - let checkout_request = transport - .requests - .iter() - .find(|request| request.url.ends_with("/backend-api/payments/checkout")) - .expect("PayPal Checkout request must be sent"); - assert!(matches!(&checkout_request.body, RequestBody::Json(body) - if body["billing_details"]["country"] == "US" - && body["billing_details"]["currency"] == "USD")); - - let payment_method_request = transport - .requests - .iter() - .find(|request| request.url.ends_with("/v1/payment_methods")) - .expect("PayPal PaymentMethod request must be sent"); - assert!(matches!(&payment_method_request.body, RequestBody::Form(form) - if form.get("billing_details[address][country]").map(String::as_str) == Some("US") - && form.get("billing_details[address][state]").map(String::as_str) == Some("CA"))); - - let mut approve_requests = 0; - for request in &transport.requests { - if request.url.ends_with("/backend-api/payments/checkout/update") { - assert!(request.proxy_url.contains("promotion.example:3020")); - assert!(request.proxy_url.contains("region-VN")); - } else if request.url.ends_with("/backend-api/payments/checkout") - || request.url.ends_with("/backend-api/sentinel/ping") - || request.url.ends_with("/backend-api/payments/checkout/approve") - || (request.url.ends_with("/v1/payment_pages/cs_paypal_pool_test") - && request.method == "GET") - { - assert!(request.proxy_url.contains("checkout.example:3010")); - assert!(request.proxy_url.contains("region-US")); - if request.url.ends_with("/backend-api/payments/checkout/approve") { - approve_requests += 1; - } - } else { - assert!( - request.proxy_url.contains("provider.example:3030"), - "provider PayPal request must use the TR pool: {}", - request.url - ); - assert!(request.proxy_url.contains("region-TR")); - } - } - assert_eq!(approve_requests, 1); - } - - #[test] - fn ideal_method_guard_accepts_nl_checkout_and_rejects_card_link_only_session() { - let supported = serde_json::json!({ - "payment_method_types": ["card", "ideal", "apple_pay"] - }); - assert_eq!( - stripe_init_payment_method_types(&supported), - vec![ - "card".to_string(), - "ideal".to_string(), - "apple_pay".to_string(), - ] - ); - assert!(ensure_ideal_is_offered(&supported, "test").is_ok()); - - let blocked = serde_json::json!({ - "payment_method_types": ["card", "link"] - }); - let error = - ensure_ideal_is_offered(&blocked, "VN-created").expect_err("iDEAL must be listed"); - assert!(error.to_string().contains("does not offer ideal")); - } - - #[tokio::test] - async fn chatgpt_return_url_is_not_successful_ideal_link() { - #[derive(Default)] - struct ChatgptReturnTransport { - requests: Vec, - init_calls: usize, - } - - #[async_trait] - impl Transport for ChatgptReturnTransport { - async fn send(&mut self, request: HttpRequest) -> Result { - self.requests.push(request.clone()); - let path = Url::parse(&request.url) - .map(|url| url.path().to_string()) - .unwrap_or_else(|_| request.url.clone()); - let body = match path.as_str() { - "/backend-api/payments/checkout" => serde_json::json!({ - "checkout_session_id": "cs_test_return", - "processor_entity": "openai_ie", - "publishable_key": "pk_REDACTED" - }), - "/v1/payment_pages/cs_test_return/init" => { - self.init_calls += 1; - serde_json::json!({ - "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_test_return", - "init_checksum": format!("checksum_return_{}", self.init_calls), - "total_summary": { "due": if self.init_calls == 1 { 2300 } else { 0 } }, - "payment_method_types": ["card", "ideal"], - "currency": "eur", - "config_id": "cfg_return" - }) - } - "/backend-api/payments/checkout/update" => { - serde_json::json!({ "success": true }) - } - "/backend-api/payments/checkout/taxes" => { - serde_json::json!({ "using_automatic_tax": true }) - } - "/v1/payment_methods" => serde_json::json!({ "id": "pm_test_return" }), - "/v1/payment_pages/cs_test_return/confirm" => serde_json::json!({ - "submission_attempt": { "state": "requires_approval" } - }), - "/backend-api/sentinel/ping" => serde_json::json!({ "status": "OK" }), - "/backend-api/payments/checkout/approve" => { - serde_json::json!({ "result": "approved" }) - } - "/v1/payment_pages/cs_test_return" if request.method == "POST" => { - serde_json::json!({}) - } - "/v1/payment_pages/cs_test_return" => serde_json::json!({ - "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://pm-redirects.stripe.com/authorize/return" } } - }), - "/authorize/return" => serde_json::json!({}), - "/" => serde_json::json!({ "not": "ideal" }), - other => panic!("unexpected request path {other}"), - }; - if path == "/authorize/return" { - let mut headers = BTreeMap::new(); - headers.insert("location".to_string(), "https://chatgpt.com/".to_string()); - return Ok(HttpResponse { - status: 302, - headers, - body: String::new(), - }); - } - Ok(HttpResponse { - status: 200, - headers: BTreeMap::new(), - body: body.to_string(), - }) - } - } - - let mut transport = ChatgptReturnTransport::default(); - let err = extract_ideal_link( - &mut transport, - ExtractInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - proxy: "http://user-region-US-sid-old-t-1:pass@proxy.example:3010".to_string(), - checkout_proxy_pool: Vec::new(), - promotion_proxy_pool: Vec::new(), - paypal_provider_proxy_pool: Vec::new(), - base_url: "http://IP_REDACTED:8792".to_string(), - link_type: "ideal".to_string(), - }, - ) - .await - .expect_err("chatgpt.com return_url must not be treated as an iDEAL link"); - - assert!( - matches!(err, ExtractError::BadResponse(ref message) if message.contains("ideal redirect")), - "unexpected error: {err}" - ); - } - - #[tokio::test] - async fn empty_token_is_rejected_before_network() { - let mut transport = FakeTransport::default(); - let err = extract_ideal_link( - &mut transport, - ExtractInput { - access_token: " ".to_string(), - proxy: String::new(), - checkout_proxy_pool: Vec::new(), - promotion_proxy_pool: Vec::new(), - paypal_provider_proxy_pool: Vec::new(), - base_url: "http://IP_REDACTED:8792".to_string(), - link_type: "ideal".to_string(), - }, - ) - .await - .expect_err("empty token should fail"); - assert!(matches!(err, ExtractError::MissingToken)); - assert!( - transport.requests.is_empty(), - "empty token must not perform network requests" - ); - } - - #[tokio::test] - async fn non_local_base_url_is_rejected_before_network() { - let mut transport = FakeTransport::default(); - let err = extract_ideal_link( - &mut transport, - ExtractInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - proxy: String::new(), - checkout_proxy_pool: Vec::new(), - promotion_proxy_pool: Vec::new(), - paypal_provider_proxy_pool: Vec::new(), - base_url: "https://collector.example.test".to_string(), - link_type: "ideal".to_string(), - }, - ) - .await - .expect_err("non-local base-url should fail before any token-bearing request"); - assert!( - matches!(err, ExtractError::UnsafeBaseUrl(_)), - "non-local base-url must be rejected explicitly" - ); - assert!( - transport.requests.is_empty(), - "non-local base-url must not perform network requests" - ); - } - - #[tokio::test] - async fn loopback_prefix_hostname_is_rejected_before_network() { - for base_url in [ - "http://IP_REDACTED.evil.test:8792", - "http://127.attacker.test:8792", - ] { - let mut transport = FakeTransport::default(); - let err = extract_ideal_link( - &mut transport, - ExtractInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - proxy: String::new(), - checkout_proxy_pool: Vec::new(), - promotion_proxy_pool: Vec::new(), - paypal_provider_proxy_pool: Vec::new(), - base_url: base_url.to_string(), - link_type: "ideal".to_string(), - }, - ) - .await - .expect_err("loopback-looking hostname should fail before any token-bearing request"); - assert!( - matches!(err, ExtractError::UnsafeBaseUrl(_)), - "{base_url} must be rejected explicitly" - ); - assert!( - transport.requests.is_empty(), - "{base_url} must not perform network requests" - ); - } - } - - #[test] - fn proxy_regions_are_rewritten_without_ip_checks() { - assert_eq!( - proxy_for_region( - "http://user-region-US-sid-old-t-1:pass@proxy.example:3010", - "VN" - ), - "http://user-region-VN-sid-old-t-1:pass@proxy.example:3010" - ); - assert_eq!( - proxy_for_region( - "http://user-region-VN-sid-old-t-1:pass@proxy.example:3010", - "NL" - ), - "http://user-region-NL-sid-old-t-1:pass@proxy.example:3010" - ); - } - - #[test] - fn extracts_pay_ideal_transactions_url_shape_from_text() { - let ideal_url = "https://pay.ideal.nl/transactions/https%3A%2F%2Ftx.ideal.nl%2F2%2FAJJSI6HAJFM3HEBSMGYLL3JTFEY?sig=TESTSIGNATURE"; - - assert_eq!( - extract_ideal_url_from_text(&format!("redirect to {ideal_url} now")).as_deref(), - Some(ideal_url) - ); - } - - #[test] - fn redirect_extraction_ignores_stripe_file_asset_urls() { - let cloudfront_asset = "https://d1wqzb5bdbcre6.cloudfront.net/65e09e3f3d30989bfaa5bb72edb65360e25b78d32fb83667a9601ad10b141676/68747470733a2f2f66696c65732e7374726970652e636f6d2f66696c65732f4d44423859574e6a6446387855476f7a4e7a644c63327849556d52695956426e66475a6662476c325a563947546b315551566c3362576834647a464c53546b33526b6335543056745357383030624d54667a314978/6d65726368616e745f69643d616363745f31506a3337374b736c4852646261506726636c69656e743d5041594d454e545f50414745"; - let redirect_url = "https://pm-redirects.stripe.com/authorize/test"; - - let asset_only_payload = serde_json::json!({ - "url": cloudfront_asset, - "client": "PAYMENT_PAGE" - }); - assert_eq!(extract_redirect_to_url(&asset_only_payload), None); - - let payload = serde_json::json!({ - "url": cloudfront_asset, - "payment_method_options": { - "ideal": { - "redirect_url": redirect_url - } - } - }); - - assert_eq!( - extract_redirect_to_url(&payload).as_deref(), - Some(redirect_url) - ); - } - - #[test] - fn source_excludes_probe_and_hooks() { - let source = include_str!("lib.rs"); - let forbidden = [ - ["api.", "ipify", ".org"].concat(), - ["ip", "who", ".is"].concat(), - ["api.", "my", "ip.com"].concat(), - ["thread::", "spawn"].concat(), - ["dae", "mon"].concat(), - ["back", "ground"].concat(), - ]; - for item in forbidden { - assert!( - !source.contains(&item), - "new Rust source must not contain {item}" - ); - } - } - - #[test] - fn frontend_html_contains_browser_contract() { - let html = frontend_html(); - - assert!(html.contains("iDEAL 链接提取器")); - assert!(html.contains("Access Token 或 session JSON")); - assert!(html.contains("提取 iDEAL 链")); - assert!(html.contains("id=\"access-token\"")); - assert!(html.contains("id=\"checkout-proxy-pool\"")); - assert!(html.contains("id=\"promotion-proxy-pool\"")); - assert!(html.contains("id=\"paypal-checkout-proxy-pool\"")); - assert!(html.contains("id=\"paypal-promotion-proxy-pool\"")); - assert!(html.contains("id=\"paypal-provider-proxy-pool\"")); - assert!(html.contains("iDEAL Checkout 主代理池(每行一个)")); - assert!(html.contains("iDEAL Promotion Update 代理池(每行一个)")); - assert!(html.contains("PayPal US Checkout / Approve 代理池(每行一个)")); - assert!(html.contains("PayPal VN Promotion Update 代理池(每行一个)")); - assert!(html.contains("PayPal TR Provider 代理池(每行一个)")); - assert!(html.contains("checkout_proxy_pool")); - assert!(html.contains("promotion_proxy_pool")); - assert!(html.contains("paypal_checkout_proxy_pool")); - assert!(html.contains("paypal_promotion_proxy_pool")); - assert!(html.contains("paypal_provider_proxy_pool")); - assert!(!html.contains("paypal_proxy")); - assert!(html.contains("data-link-type=\"ideal\"")); - assert!(html.contains("data-link-type=\"paypal\"")); - assert!(html.contains("/api/extract")); - assert!(html.contains("排队中")); - assert!(html.contains("正在执行完整 iDEAL 链路")); - assert!(html.contains("id=\"long-url\"")); - assert!(html.contains("overflow-wrap: anywhere")); - assert!(html.contains("/cancel")); - assert!(html.contains("link_type: currentLinkType")); - assert!(!html.contains("localStorage")); - assert!(!html.contains("UPI")); - } - - #[test] - fn env_proxy_parser_reads_default_proxy_without_exposing_other_values() { - let proxy = default_proxy_from_env_text( - r#" - OPENAI_PAY_PROVIDER_PROXY=http://provider.example - OPENAI_PAY_DEFAULT_PROXY="http://user-region-US-sid-old-t-1:pass@proxy.example:3010" - "#, - ); - - assert_eq!( - proxy, - "http://user-region-US-sid-old-t-1:pass@proxy.example:3010" - ); - } - - #[test] - fn api_input_uses_submitted_proxy_pools_and_default_base_url() { - let input = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010\ncheckout.example:3010".to_string(), - promotion_proxy_pool: "http://promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }) - .expect("both submitted pools should be accepted"); - - assert_eq!(input.access_token, "at_test"); - assert_eq!(input.proxy, "http://checkout.example:3010"); - assert_eq!(input.checkout_proxy_pool, vec!["http://checkout.example:3010"]); - assert_eq!(input.promotion_proxy_pool, vec!["http://promotion.example:3010"]); - assert!(input.base_url.is_empty()); - assert_eq!(input.link_type, "ideal"); - } - - #[test] - fn api_input_exposes_three_paypal_proxy_pools() { - let input = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: - "checkout-one.example:3010\ncheckout-one.example:3010\ncheckout-two.example:3010" - .to_string(), - paypal_promotion_proxy_pool: "promotion.example:3020".to_string(), - paypal_provider_proxy_pool: "provider.example:3030".to_string(), - }) - .expect("valid PayPal pools should be accepted"); - - assert_eq!(input.proxy, "http://checkout-one.example:3010"); - assert_eq!( - input.checkout_proxy_pool, - vec![ - "http://checkout-one.example:3010", - "http://checkout-two.example:3010" - ] - ); - assert_eq!( - input.promotion_proxy_pool, - vec!["http://promotion.example:3020"] - ); - assert_eq!( - input.paypal_provider_proxy_pool, - vec!["http://provider.example:3030"] - ); - assert_eq!(input.link_type, "paypal"); - } - - #[test] - fn api_input_rejects_missing_invalid_paypal_pools_and_unknown_link_type() { - let missing_checkout = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: "promotion.example:3020".to_string(), - paypal_provider_proxy_pool: "provider.example:3030".to_string(), - }); - assert!(matches!( - missing_checkout, - Err(ExtractError::MissingPaypalCheckoutProxyPool) - )); - - let missing_promotion = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: "checkout.example:3010".to_string(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: "provider.example:3030".to_string(), - }); - assert!(matches!( - missing_promotion, - Err(ExtractError::MissingPaypalPromotionProxyPool) - )); - - let missing_provider = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: "checkout.example:3010".to_string(), - paypal_promotion_proxy_pool: "promotion.example:3020".to_string(), - paypal_provider_proxy_pool: String::new(), - }); - assert!(matches!( - missing_provider, - Err(ExtractError::MissingPaypalProviderProxyPool) - )); - - let invalid_checkout = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: "secret-user:secret-pass@bad host:3010".to_string(), - paypal_promotion_proxy_pool: "promotion.example:3020".to_string(), - paypal_provider_proxy_pool: "provider.example:3030".to_string(), - }); - assert!(matches!( - &invalid_checkout, - Err(ExtractError::InvalidPaypalCheckoutProxy(1)) - )); - assert!(!invalid_checkout.unwrap_err().to_string().contains("secret-user")); - - let invalid_promotion = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: "checkout.example:3010".to_string(), - paypal_promotion_proxy_pool: "secret-user:secret-pass@bad host:3010".to_string(), - paypal_provider_proxy_pool: "provider.example:3030".to_string(), - }); - assert!(matches!( - &invalid_promotion, - Err(ExtractError::InvalidPaypalPromotionProxy(1)) - )); - assert!(!invalid_promotion - .unwrap_err() - .to_string() - .contains("secret-user")); - - let invalid_provider = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("paypal".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: "checkout.example:3010".to_string(), - paypal_promotion_proxy_pool: "promotion.example:3020".to_string(), - paypal_provider_proxy_pool: "secret-user:secret-pass@bad host:3010".to_string(), - }); - assert!(matches!( - &invalid_provider, - Err(ExtractError::InvalidPaypalProviderProxy(1)) - )); - assert!(!invalid_provider - .unwrap_err() - .to_string() - .contains("secret-user")); - - let unsupported = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: Some("upi".to_string()), - checkout_proxy_pool: String::new(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }); - assert!(matches!( - unsupported, - Err(ExtractError::BadResponse(ref detail)) if detail == "unsupported link_type: upi" - )); - } - - #[test] - fn proxy_pool_parser_is_line_based_normalized_and_order_preserving() { - assert_eq!( - parse_proxy_pool( - " host-one.example:8000 \r\n\r\nhttp://user:pass@host-two.example:9000\n host-one.example:8000 ", - ProxyPoolKind::Checkout, - ) - .expect("valid lines should parse"), - vec![ - "http://host-one.example:8000".to_string(), - "http://user:pass@host-two.example:9000".to_string(), - ] - ); - assert!(matches!( - parse_proxy_pool( - "one.example:80,two.example:81", - ProxyPoolKind::Promotion, - ), - Err(ExtractError::InvalidPromotionProxy(1)) - )); - } - - #[test] - fn api_input_requires_both_proxy_pools() { - let missing_checkout = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: None, - checkout_proxy_pool: String::new(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }); - assert!(matches!( - missing_checkout, - Err(ExtractError::MissingCheckoutProxyPool) - )); - - let missing_promotion = extract_input_for_api(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: String::new(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }); - assert!(matches!( - missing_promotion, - Err(ExtractError::MissingPromotionProxyPool) - )); - } - - #[tokio::test] - async fn api_config_matches_locked_config() { - let axum::Json(config) = api_config().await; - - assert_eq!(config, locked_config()); - assert_eq!(config.client_fingerprint, "apple-safari"); - assert_eq!(config.checkout_proxy_region, "NL"); - assert_eq!(config.promotion_proxy_region, Some("VN")); - assert_eq!(config.provider_proxy_region, "NL"); - assert_eq!(config.approve_proxy_region, "NL"); - assert_eq!(config.approve_max_attempts, 20); - assert_eq!(config.approve_concurrency, 1); - - let paypal = config_for_link_type(LinkType::Paypal); - assert_eq!(paypal.billing_country, "US"); - assert_eq!(paypal.currency, "USD"); - assert_eq!(paypal.checkout_proxy_region, "US"); - assert_eq!(paypal.promotion_proxy_region, Some("VN")); - assert_eq!(paypal.provider_proxy_region, "TR"); - assert_eq!(paypal.approve_proxy_region, "US"); - assert_eq!(paypal.approve_max_attempts, 1); - } - - #[cfg(feature = "postgres-integration-tests")] - #[tokio::test] - async fn api_extract_rejects_empty_token_before_network() { - let (state, _receiver) = AppState::new_unstarted_for_test(1); - let headers = login_test_user(&state, "linuxdo-1", DEFAULT_CDK_USES); - let (status, axum::Json(response)) = api_extract( - State(state), - headers, - axum::Json(ExtractApiInput { - access_token: " ".to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - - assert_eq!(status, axum::http::StatusCode::BAD_REQUEST); - assert!(!response.ok); - assert_eq!(response.error.as_deref(), Some("Access Token is required")); - assert!(response.output.is_none()); - assert!(response.job.is_none()); - } - - #[cfg(feature = "postgres-integration-tests")] - #[tokio::test] - async fn api_extract_enqueues_job_and_reports_queue_position() { - let (state, _receiver) = AppState::new_unstarted_for_test(2); - let headers = login_test_user(&state, "linuxdo-1", DEFAULT_CDK_USES); - let (status, axum::Json(response)) = api_extract( - State(state.clone()), - headers.clone(), - axum::Json(ExtractApiInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - - assert_eq!(status, axum::http::StatusCode::ACCEPTED); - assert!(response.ok); - assert!(response.output.is_none()); - let job = response.job.expect("queued response should include job"); - assert_eq!(job.status, ExtractJobStatus::Queued); - assert_eq!(job.position, 1); - assert_eq!(job.queue_size, 1); - - let (status, axum::Json(response)) = - api_extract_status(State(state), headers, Path(job.job_id)).await; - assert_eq!(status, axum::http::StatusCode::OK); - assert!(response.ok); - let job = response.job.expect("status response should include job"); - assert_eq!(job.status, ExtractJobStatus::Queued); - assert_eq!(job.position, 1); - } - - #[cfg(feature = "postgres-integration-tests")] - #[tokio::test] - async fn api_extract_returns_busy_when_queue_is_full() { - let (state, _receiver) = AppState::new_unstarted_for_test(1); - let headers = login_test_user(&state, "linuxdo-1", DEFAULT_CDK_USES); - let token = "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig".to_string(); - - let (status, axum::Json(first)) = api_extract( - State(state.clone()), - headers.clone(), - axum::Json(ExtractApiInput { - access_token: token.clone(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - assert_eq!(status, axum::http::StatusCode::ACCEPTED); - assert!(first.ok); - - let (status, axum::Json(second)) = api_extract( - State(state), - headers, - axum::Json(ExtractApiInput { - access_token: token, - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - assert_eq!(status, axum::http::StatusCode::TOO_MANY_REQUESTS); - assert!(!second.ok); - assert_eq!(second.error.as_deref(), Some("队列已满,请稍后再试。")); - assert!(second.output.is_none()); - assert!(second.job.is_none()); - } - - #[cfg(feature = "postgres-integration-tests")] - #[tokio::test] - async fn api_extract_requires_linuxdo_login() { - let (state, _receiver) = AppState::new_unstarted_for_test(1); - - let (status, axum::Json(response)) = api_extract( - State(state), - HeaderMap::new(), - axum::Json(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - - assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED); - assert!(!response.ok); - assert_eq!(response.error.as_deref(), Some("请先使用 LinuxDo 登录。")); - } - - #[cfg(feature = "postgres-integration-tests")] - #[tokio::test] - async fn api_extract_rejects_when_cdk_has_no_available_uses() { - let (state, _receiver) = AppState::new_unstarted_for_test(1); - let headers = login_test_user(&state, "linuxdo-1", 0); - - let (status, axum::Json(response)) = api_extract( - State(state), - headers, - axum::Json(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - - assert_eq!(status, axum::http::StatusCode::FORBIDDEN); - assert!(!response.ok); - assert_eq!(response.error.as_deref(), Some("CDK 使用次数已用完。")); - } - - #[cfg(feature = "postgres-integration-tests")] - #[tokio::test] - async fn api_extract_status_is_visible_only_to_job_owner() { - let (state, _receiver) = AppState::new_unstarted_for_test(2); - let owner_headers = login_test_user(&state, "linuxdo-owner", DEFAULT_CDK_USES); - let other_headers = login_test_user(&state, "linuxdo-other", DEFAULT_CDK_USES); - - let (status, axum::Json(response)) = api_extract( - State(state.clone()), - owner_headers, - axum::Json(ExtractApiInput { - access_token: "at_test".to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }), - ) - .await; - assert_eq!(status, axum::http::StatusCode::ACCEPTED); - let job_id = response.job.expect("job should be queued").job_id; - - let (status, axum::Json(response)) = - api_extract_status(State(state), other_headers, Path(job_id)).await; - - assert_eq!(status, axum::http::StatusCode::NOT_FOUND); - assert!(!response.ok); - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn linuxdo_login_binds_one_ten_use_cdk_per_account() { - let auth = AuthStore::in_memory(); - let (_, first) = auth - .login_linuxdo_user(test_linuxdo_user("linuxdo-1")) - .expect("login should bind cdk"); - auth.reserve_use(&first.linuxdo_id) - .expect("first use should reserve"); - auth.complete_reserved_use(&first.linuxdo_id, true); - let (_, second) = auth - .login_linuxdo_user(test_linuxdo_user("linuxdo-1")) - .expect("second login should reuse cdk"); - - assert_eq!(first.cdk, second.cdk); - assert_eq!(second.total_uses, DEFAULT_CDK_USES); - assert_eq!(second.remaining_uses, DEFAULT_CDK_USES - 1); - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn cdk_use_is_charged_only_on_successful_extraction() { - let auth = AuthStore::in_memory(); - let (_, user) = auth - .login_linuxdo_user(test_linuxdo_user("linuxdo-1")) - .expect("login should bind cdk"); - - auth.reserve_use(&user.linuxdo_id) - .expect("use should reserve"); - auth.complete_reserved_use(&user.linuxdo_id, false); - assert_eq!( - auth_user(&auth, &user.linuxdo_id).remaining_uses, - DEFAULT_CDK_USES - ); - - auth.reserve_use(&user.linuxdo_id) - .expect("use should reserve"); - auth.complete_reserved_use(&user.linuxdo_id, true); - assert_eq!( - auth_user(&auth, &user.linuxdo_id).remaining_uses, - DEFAULT_CDK_USES - 1 - ); - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn auth_store_invalid_json_fails_loudly() { - let temp_dir = tempfile::tempdir().expect("temp dir should be created"); - let auth_path = temp_dir.path().join("linuxdo-auth-store.json"); - fs::write(&auth_path, "not json").expect("invalid auth store should be written"); - - let result = std::panic::catch_unwind(|| AuthStore::new(auth_path.clone())); - - assert!(result.is_err()); - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn auth_store_persists_sessions_without_temp_file_leftovers() { - let temp_dir = tempfile::tempdir().expect("temp dir should be created"); - let auth_path = temp_dir.path().join("linuxdo-auth-store.json"); - let auth = AuthStore::new(auth_path.clone()); - let (session, user) = auth - .login_linuxdo_user(test_linuxdo_user("linuxdo-1")) - .expect("login should persist auth store"); - - let reloaded = AuthStore::new(auth_path.clone()); - let reloaded_user = reloaded - .user_from_session(&session) - .expect("persisted session should reload"); - - assert_eq!(reloaded_user.cdk, user.cdk); - assert_eq!(reloaded_user.remaining_uses, DEFAULT_CDK_USES); - let files = fs::read_dir(temp_dir.path()) - .expect("auth dir should be readable") - .map(|entry| { - entry - .expect("dir entry should be readable") - .file_name() - .to_string_lossy() - .into_owned() - }) - .collect::>(); - assert_eq!(files, vec!["linuxdo-auth-store.json"]); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = fs::metadata(&auth_path) - .expect("auth store metadata should be readable") - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o600); - } - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn oauth_state_expires_and_is_removed_on_consume() { - let auth = AuthStore::in_memory(); - let state = auth.create_oauth_state(); - { - let mut data = auth.data.lock().expect("auth store mutex poisoned"); - data.oauth_states - .get_mut(&state) - .expect("oauth state should exist") - .created_at_secs = now_epoch_secs().saturating_sub(OAUTH_STATE_TTL_SECS + 1); - } - - assert!(!auth.consume_oauth_state(&state)); - let data = auth.data.lock().expect("auth store mutex poisoned"); - assert!(!data.oauth_states.contains_key(&state)); - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn oauth_state_creation_prunes_expired_and_caps_live_states() { - let auth = AuthStore::in_memory(); - { - let mut data = auth.data.lock().expect("auth store mutex poisoned"); - data.oauth_states.insert( - "expired-state".to_string(), - OAuthStateRecord { - created_at_secs: now_epoch_secs().saturating_sub(OAUTH_STATE_TTL_SECS + 1), - }, - ); - } - let mut newest_state = String::new(); - for _ in 0..(MAX_OAUTH_STATES + 25) { - newest_state = auth.create_oauth_state(); - } - - let data = auth.data.lock().expect("auth store mutex poisoned"); - assert!(data.oauth_states.len() <= MAX_OAUTH_STATES); - assert!(data.oauth_states.contains_key(&newest_state)); - assert!(!data.oauth_states.contains_key("expired-state")); - } - - #[cfg(feature = "postgres-integration-tests")] - #[test] - fn quota_reservation_guard_releases_pending_use_on_drop() { - let auth = AuthStore::in_memory(); - let (_, user) = auth - .login_linuxdo_user(test_linuxdo_user("linuxdo-1")) - .expect("login should bind cdk"); - auth.reserve_use(&user.linuxdo_id) - .expect("use should reserve"); - let jobs = Arc::new(StdMutex::new(BTreeMap::::new())); - { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - insert_test_job(&mut jobs, "job-1", ExtractJobStatus::Running, 1); - } - - { - let _guard = QuotaReservationGuard::new( - auth.clone(), - Arc::clone(&jobs), - "job-1".to_string(), - user.linuxdo_id.clone(), - ); - } - - let user = auth_user(&auth, &user.linuxdo_id); - assert_eq!(user.pending_uses, 0); - assert_eq!(user.remaining_uses, DEFAULT_CDK_USES); - let snapshot = snapshot_from_jobs(&jobs, "job-1").expect("job should remain visible"); - assert_eq!(snapshot.status, ExtractJobStatus::Failed); - assert!(snapshot - .error - .as_deref() - .expect("interrupted job should include error") - .contains("已释放")); - } - - #[tokio::test] - async fn api_extract_uses_default_official_base_url() { - let response = extract_input_for_api( - ExtractApiInput { - access_token: "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImpAZXhhbXBsZS5jb20ifQ.sig" - .to_string(), - link_type: None, - checkout_proxy_pool: "checkout.example:3010".to_string(), - promotion_proxy_pool: "promotion.example:3010".to_string(), - paypal_checkout_proxy_pool: String::new(), - paypal_promotion_proxy_pool: String::new(), - paypal_provider_proxy_pool: String::new(), - }, - ) - .expect("valid pools should be accepted"); - - assert!(response.base_url.is_empty()); - } - - #[test] - fn queue_config_defaults_to_100_workers_and_1000_capacity() { - let config = QueueConfig::default(); - - assert_eq!(config.worker_count, 100); - assert_eq!(config.queue_capacity, 1000); - } - - #[test] - fn queue_config_reads_json_and_normalizes_zero_values() { - let config = queue_config_from_json( - r#" - { - "worker_count": 12, - "queue_capacity": 345 - } - "#, - ) - .expect("queue config JSON should parse"); - assert_eq!(config.worker_count, 12); - assert_eq!(config.queue_capacity, 345); - - let config = queue_config_from_json( - r#" - { - "worker_count": 0, - "queue_capacity": 0 - } - "#, - ) - .expect("queue config JSON should parse"); - assert_eq!(config.worker_count, 1); - assert_eq!(config.queue_capacity, 1); - } - - #[test] - fn queue_config_finished_retention_matches_workers_plus_waiting_capacity() { - assert_eq!(QueueConfig::default().finished_job_retained(), 1100); - assert_eq!( - QueueConfig { - worker_count: 2, - queue_capacity: 3, - } - .finished_job_retained(), - MIN_FINISHED_JOB_RETAINED - ); - } - - #[test] - fn prune_finished_jobs_keeps_finished_result_when_backlog_is_large() { - let jobs = Arc::new(StdMutex::new(BTreeMap::::new())); - { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - for order in 1..=100 { - insert_test_job( - &mut jobs, - &format!("queued-{order}"), - ExtractJobStatus::Queued, - order, - ); - } - insert_test_job(&mut jobs, "completed", ExtractJobStatus::Completed, 101); - } - - prune_finished_jobs(&jobs, MIN_FINISHED_JOB_RETAINED); - - let jobs = jobs.lock().expect("queue mutex poisoned"); - assert!(jobs.contains_key("completed")); - assert_eq!(jobs.len(), 101); - } - - #[test] - fn prune_finished_jobs_removes_only_oldest_excess_finished_jobs() { - let jobs = Arc::new(StdMutex::new(BTreeMap::::new())); - { - let mut jobs = jobs.lock().expect("queue mutex poisoned"); - for order in 1..=5 { - insert_test_job( - &mut jobs, - &format!("finished-{order}"), - ExtractJobStatus::Completed, - order, - ); - } - insert_test_job(&mut jobs, "queued", ExtractJobStatus::Queued, 6); - insert_test_job(&mut jobs, "running", ExtractJobStatus::Running, 7); - } - - prune_finished_jobs(&jobs, 3); - - let jobs = jobs.lock().expect("queue mutex poisoned"); - assert!(!jobs.contains_key("finished-1")); - assert!(!jobs.contains_key("finished-2")); - assert!(jobs.contains_key("finished-3")); - assert!(jobs.contains_key("finished-4")); - assert!(jobs.contains_key("finished-5")); - assert!(jobs.contains_key("queued")); - assert!(jobs.contains_key("running")); - } - - #[test] - fn queue_config_missing_file_writes_default_config() { - let temp_dir = tempfile::tempdir().expect("temp dir should be created"); - let config_path = temp_dir.path().join("queue-config.json"); - - let config = configured_queue_config_from_path(&config_path); - - assert_eq!(config, QueueConfig::default()); - let written = fs::read_to_string(config_path).expect("default config should be written"); - assert!(written.contains("\"worker_count\": 100")); - assert!(written.contains("\"queue_capacity\": 1000")); - } - - #[test] - fn queue_config_file_override_is_loaded() { - let temp_dir = tempfile::tempdir().expect("temp dir should be created"); - let config_path = temp_dir.path().join("queue-config.json"); - fs::write( - &config_path, - r#" - { - "worker_count": 7, - "queue_capacity": 11 - } - "#, - ) - .expect("override config should be written"); - - let config = configured_queue_config_from_path(&config_path); - - assert_eq!(config.worker_count, 7); - assert_eq!(config.queue_capacity, 11); - } - - fn insert_test_job( - jobs: &mut BTreeMap, - job_id: &str, - status: ExtractJobStatus, - order: u64, - ) { - jobs.insert( - job_id.to_string(), - ExtractJob { - status, - order, - steps: Vec::new(), - output: None, - error: None, - }, - ); - } - - #[cfg(feature = "postgres-integration-tests")] - fn login_test_user(state: &AppState, linuxdo_id: &str, remaining_uses: usize) -> HeaderMap { - let (session, user) = state - .auth - .login_linuxdo_user(test_linuxdo_user(linuxdo_id)) - .expect("test login should succeed"); - { - let mut data = state.auth.data.lock().expect("auth store mutex poisoned"); - let record = data - .users - .get_mut(&user.linuxdo_id) - .expect("test user should exist"); - record.remaining_uses = remaining_uses; - record.pending_uses = 0; - } - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(&format!("{SESSION_COOKIE_NAME}={session}")) - .expect("test cookie should be valid"), - ); - headers - } - - #[cfg(feature = "postgres-integration-tests")] - fn test_linuxdo_user(linuxdo_id: &str) -> LinuxDoUserInfo { - LinuxDoUserInfo { - id: Value::String(linuxdo_id.to_string()), - username: format!("user-{linuxdo_id}"), - name: format!("User {linuxdo_id}"), - active: true, - trust_level: 1, - silenced: false, - } - } - - #[cfg(feature = "postgres-integration-tests")] - fn auth_user(auth: &AuthStore, linuxdo_id: &str) -> AuthUserSnapshot { - let data = auth.data.lock().expect("auth store mutex poisoned"); - data.users - .get(linuxdo_id) - .expect("auth user should exist") - .snapshot() - } -} diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 0e7007e7ca56d49c6d1d8b7872bd088675ede25b..0000000000000000000000000000000000000000 --- a/src/main.rs +++ /dev/null @@ -1,74 +0,0 @@ -use clap::{Parser, Subcommand}; -use ideal_link_extractor_rust::app_router; -use std::{net::SocketAddr, process::ExitCode}; - -#[derive(Debug, Parser)] -#[command(name = "ideal-link-extractor-rust")] -struct Cli { - #[command(subcommand)] - command: Command, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn serve_command_parses_listen_address() { - let cli = Cli::try_parse_from([ - "ideal-link-extractor-rust", - "serve", - "--listen", - "IP_REDACTED:8794", - ]) - .expect("serve command should parse"); - - let Command::Serve { listen } = cli.command; - assert_eq!(listen.to_string(), "IP_REDACTED:8794"); - } - - #[test] - fn extract_command_is_not_available() { - let error = Cli::try_parse_from([ - "ideal-link-extractor-rust", - "extract", - "--access-token-file", - "../at.txt", - ]) - .expect_err("direct extraction must not be available from the CLI"); - - assert_eq!(error.kind(), clap::error::ErrorKind::InvalidSubcommand); - } -} - -#[derive(Debug, Subcommand)] -enum Command { - Serve { - #[arg(long, default_value = "IP_REDACTED:8793")] - listen: SocketAddr, - }, -} - -#[tokio::main] -async fn main() -> ExitCode { - let cli = Cli::parse(); - match cli.command { - Command::Serve { listen } => { - let listener = match tokio::net::TcpListener::bind(listen).await { - Ok(listener) => listener, - Err(error) => { - eprintln!("failed to bind {listen}: {error}"); - return ExitCode::from(2); - } - }; - println!("serving http://{listen}"); - match axum::serve(listener, app_router().await).await { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!("server failed: {error}"); - ExitCode::from(1) - } - } - } - } -} diff --git a/start.py b/start.py new file mode 100644 index 0000000000000000000000000000000000000000..259e7de772754a04086f1379e04edc54d78ec5f6 --- /dev/null +++ b/start.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +""" +qwen2API Enterprise Gateway 启动脚本 + +前端: Vite dev server http://localhost:5174 (热更新) +后端: uvicorn http://localhost:7860 (API 网关) +""" +import os +import sys +import subprocess +import time +import signal +from pathlib import Path + +WORKSPACE_DIR = Path(__file__).parent.absolute() +BACKEND_DIR = WORKSPACE_DIR / "backend" +FRONTEND_DIR = WORKSPACE_DIR / "frontend" +LOGS_DIR = WORKSPACE_DIR / "logs" +DATA_DIR = WORKSPACE_DIR / "data" + + +def ensure_dirs(): + LOGS_DIR.mkdir(exist_ok=True) + DATA_DIR.mkdir(exist_ok=True) + + +def check_python(): + if sys.version_info < (3, 10): + print("❌ 需要 Python 3.10+,当前版本:", sys.version) + sys.exit(1) + + +def install_backend_deps(): + print("⚡ [1/4] 安装后端依赖...") + env = os.environ.copy() + env["PYTHONPATH"] = str(WORKSPACE_DIR) + try: + subprocess.check_call( + [sys.executable, "-m", "pip", "install", "-r", "requirements.txt", "-q"], + cwd=BACKEND_DIR, + env=env, + ) + print("✓ 后端依赖已就绪") + except Exception as e: + print(f"⚠ 后端依赖安装异常: {e}") + + +def fetch_browser(): + print("⚡ [2/4] 检查注册功能所需的 Camoufox 浏览器内核...") + env = os.environ.copy() + env["PYTHONPATH"] = str(WORKSPACE_DIR) + try: + result = subprocess.run( + [sys.executable, "-m", "camoufox", "path"], + capture_output=True, text=True, timeout=10, env=env, + ) + if result.returncode == 0 and result.stdout.strip(): + print("✓ 浏览器内核已存在,跳过下载") + return + except Exception: + pass + print(" -> 正在下载 Camoufox 内核(仅注册/激活账号时会使用,请耐心等待)...") + try: + subprocess.check_call( + [sys.executable, "-m", "camoufox", "fetch"], + cwd=WORKSPACE_DIR, + env=env, + ) + print("✓ 浏览器内核下载完成") + except Exception as e: + print(f"⚠ 浏览器内核下载异常: {e}") + + +def start_frontend() -> subprocess.Popen: + print("⚡ [3/4] 启动前端开发服务器...") + is_windows = os.name == "nt" + + if not (FRONTEND_DIR / "node_modules").exists(): + print(" -> 正在执行 npm install...") + try: + subprocess.check_call( + "npm install" if is_windows else ["npm", "install"], + cwd=FRONTEND_DIR, + shell=is_windows, + ) + except subprocess.CalledProcessError as e: + print(f"❌ npm install 失败: {e}") + sys.exit(1) + + proc = subprocess.Popen( + "npm run dev" if is_windows else ["npm", "run", "dev"], + cwd=FRONTEND_DIR, + shell=is_windows, + ) + print(f"✓ 前端已启动 (PID: {proc.pid}) → http://127.0.0.1:5174") + return proc + + +def kill_port(port: int): + """Kill any process occupying the given port.""" + try: + if os.name == "nt": + result = subprocess.run( + ["netstat", "-ano", "-p", "TCP"], + capture_output=True, text=True, timeout=5 + ) + for line in result.stdout.splitlines(): + if f":{port} " in line and "LISTENING" in line: + pid = line.strip().split()[-1] + if pid.isdigit(): + subprocess.run(["taskkill", "/F", "/PID", pid], capture_output=True) + print(f" -> 已终止占用 {port} 端口的旧进程 (PID: {pid})") + time.sleep(1) + return + else: + result = subprocess.run( + ["lsof", "-ti", f"tcp:{port}"], + capture_output=True, text=True, timeout=5 + ) + pid = result.stdout.strip() + if pid: + subprocess.run(["kill", "-9", pid], capture_output=True) + print(f" -> 已终止占用 {port} 端口的旧进程 (PID: {pid})") + time.sleep(1) + except Exception: + pass + + +def start_backend() -> subprocess.Popen: + print("⚡ [4/4] 启动后端服务...") + env = os.environ.copy() + env["PYTHONPATH"] = str(WORKSPACE_DIR) + env["PYTHONIOENCODING"] = "utf-8" + env["PYTHONUTF8"] = "1" + + port = env.get("PORT", "7860") + workers = env.get("WORKERS", "1") + kill_port(int(port)) + + proc = subprocess.Popen( + [ + sys.executable, "-m", "uvicorn", + "backend.main:app", + "--host", "0.0.0.0", + "--port", port, + "--workers", workers, + ], + cwd=WORKSPACE_DIR, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + bufsize=0, + ) + print(f"✓ 后端进程已启动 (PID: {proc.pid}),正在等待服务完成初始化...") + + import threading + ready_event = threading.Event() + + def read_output(): + for line in iter(proc.stdout.readline, b""): + try: + decoded = line.decode("utf-8", errors="replace") + except Exception: + decoded = str(line) + print(decoded, end="") + if "Application startup complete" in decoded or "服务已完全就绪" in decoded: + ready_event.set() + + threading.Thread(target=read_output, daemon=True).start() + + started = ready_event.wait(timeout=300) + if not started: + print("⚠ 后端初始化超时,服务可能未完全就绪") + else: + print("✓ 服务已完全就绪") + + return proc + + +def main(): + ensure_dirs() + check_python() + install_backend_deps() + fetch_browser() + backend_proc = start_backend() + frontend_proc = start_frontend() + + port = os.environ.get("PORT", "7860") + print() + print("=" * 50) + print(" qwen2API 已上线") + print(f" 前端 WebUI: http://127.0.0.1:5174") + print(f" 后端 API: http://127.0.0.1:{port}") + print("=" * 50) + print(" 按 Ctrl+C 停止所有服务") + print() + + def signal_handler(sig, frame): + print("\n正在关闭服务...") + for p in (backend_proc, frontend_proc): + try: + p.terminate() + except Exception: + pass + backend_proc.wait() + print("服务已停止") + sys.exit(0) + + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) + + try: + while True: + if backend_proc.poll() is not None: + print(f"❌ 后端进程异常退出 (退出码: {backend_proc.returncode})") + break + if frontend_proc.poll() is not None: + print(f"❌ 前端进程异常退出 (退出码: {frontend_proc.returncode})") + break + time.sleep(1) + except KeyboardInterrupt: + pass + finally: + for p in (backend_proc, frontend_proc): + try: + if p.poll() is None: + p.terminate() + except Exception: + pass + + +if __name__ == "__main__": + main()