qwenwork.ai: HTTP autoreg, API reverse notes, OpenAI-compatible shim
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
accounts.jsonl
|
||||
used_codes.txt
|
||||
*.log
|
||||
__pycache__/
|
||||
.2cap_key
|
||||
.env
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Gothbreach
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,79 @@
|
||||
# qwenwork-autoreg
|
||||
|
||||
Autoreg + private API reverse for **qwenwork.ai** (Qwen Work): HTTP-only account farm, OpenAI-compatible shim, full protocol notes.
|
||||
No browser needed except captcha, which is solved through 2captcha.
|
||||
|
||||
```
|
||||
farm.py autoreg / login -> accounts.jsonl {email, jwt}
|
||||
qw_shim.py OpenAI-compatible gateway (:48981 /v1/chat/completions)
|
||||
api.md reverse-engineered API reference
|
||||
```
|
||||
|
||||
## Models (server catalog, `GET /api/chat-modes`)
|
||||
|
||||
| mode key | price_factor | notes |
|
||||
|---|---|---|
|
||||
| `kimi-k3.1-pro` | 2.6 | vision, 1M ctx |
|
||||
| `qwen3.8-max` | 1.9 | vision |
|
||||
| `qwen4-max` | 1.4 | vision, anthropic-format |
|
||||
| `glm-5.3` | 1.3 | |
|
||||
| `gpt-6.1-sol` | 1.0 | vision |
|
||||
| `deepseek-v4.1-flash`, `deepseek-flash` | 0.2 | |
|
||||
| `glm-5.3-flash` | 0.2 | vision |
|
||||
| `minimax-m3.1-flash` | 0.2 | vision, anthropic-format |
|
||||
| `qwen3.8-flash` | 0.1 | default |
|
||||
| `flash` / `advanced` / `pro` | aliases | rank tiers |
|
||||
|
||||
Measured turn price from `/user/billings`: **0.016 – 0.044 credit** for `flash`.
|
||||
Free tier advertises 500 starter + 200 daily credits -> tens of thousands of turns in theory.
|
||||
|
||||
## Autoreg flow (plain HTTP, no JS)
|
||||
|
||||
1. **Captcha** — Aliyun Captcha v3, solved with 2captcha task type `AlibabaTaskProxyless`
|
||||
(`sceneId=l47rwlyt`, `prefix=13n1x6`, `region=ga`, `apiGetLib=https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js?t=2035`).
|
||||
2. `POST /auth/email-codes {email, purpose:"registration", captcha_token}` — 200 `{"code":"ok"}`.
|
||||
**`captcha_token` must be the whole 2captcha `solution` object serialised as a JSON string** —
|
||||
an object body gives 400, `solution.data` alone gives 403 `human verification failed`.
|
||||
3. read the 6-digit code from the mailbox over IMAP (qwenwork mail, `used_codes.txt` guards against
|
||||
reusing someone else's code inside the same minute).
|
||||
4. `POST /auth/local/register {email, code, notification:false}` -> `{"created":true,"user":{...}}`,
|
||||
JWT lands in cookie `token` (403 chars).
|
||||
5. Existing address -> `409 email-exists`; use `POST /auth/local/login {email, code}`.
|
||||
|
||||
```bash
|
||||
export QW_2CAP=~/.2cap_key QW_GMAIL=you@gmail.com QW_GMAIL_PASS=app-password
|
||||
python farm.py you+qw1@gmail.com --register
|
||||
python farm.py you+qw1@gmail.com --login # if the address already exists
|
||||
```
|
||||
|
||||
## Shim
|
||||
|
||||
```bash
|
||||
QW_POOL=./accounts.jsonl QW_PORT=48981 python qw_shim.py
|
||||
curl -s localhost:48981/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"qw-flash","messages":[{"role":"user","content":"hi"}]}'
|
||||
```
|
||||
|
||||
`402`/`401`/`403` from upstream puts the account on a 15-minute cooldown and the request is retried
|
||||
on the next account. `mode` is mapped from the OpenAI model name; unknown names -> 404.
|
||||
|
||||
## Known blocker: credit hold
|
||||
|
||||
When a chat session is created, QwenWork **blocks the whole remaining balance** on that account
|
||||
(`/user/billings` -> `{"type":"Blocked","amount":-699.83,"detail":{"title":"Credits blocked"}}`)
|
||||
if the turn is not completed through the WebSocket session protocol. The hold is *not* released by
|
||||
`DELETE /api/chat-sessions/{id}`, `PATCH`, or any REST endpoint we found; REST sessions also keep
|
||||
`end_time=null` forever. Practically: one botched/half-read session zeroes the account.
|
||||
|
||||
Mitigation used here: wait for a real `agent_message_chunk` (not just `result/prompt_response`),
|
||||
close the session afterwards, and never issue a second session on an account whose previous turn
|
||||
returned no text. Proper fix is the `/api/chat-ws` protobuf session lifecycle.
|
||||
|
||||
## Notes
|
||||
|
||||
- `qwenwork.cn` has email login disabled (`/auth/email-codes` -> 404); CN entry goes through Alibaba
|
||||
fast-auth (needs a mainland account/phone).
|
||||
- Starter credits stopped being granted after ~2026-11-20 20:50 UTC in our tests; accounts created
|
||||
later report `remaining 0, exceeded true` and `402 INSUFFICIENT_RESOURCES` on session start.
|
||||
- Google OAuth entry exists: `/auth/google` -> accounts.google.com, `redirect_uri=/oauth-callback/google`,
|
||||
client_id `376662729962-6p89qbb0nd7e2vqr2da3jd7315mbnvdn`.
|
||||
@@ -0,0 +1,115 @@
|
||||
# qwenwork.ai — API reference (reverse engineered)
|
||||
|
||||
Base: `https://qwenwork.ai`. Web client: Vite SPA at `/app`, manifest at `/app/.vite/manifest.json`
|
||||
(843 entries, 414 JS chunks).
|
||||
|
||||
Auth: JWT in cookie `token` (403 chars) **and** `Authorization: Bearer <jwt>`.
|
||||
Client headers that matter: `Origin`, `Referer: <base>/app/`, `X-Client-Source: web`,
|
||||
`X-Mule-Language: en-US`.
|
||||
|
||||
## Registration / auth
|
||||
|
||||
| method | path | body / notes |
|
||||
|---|---|---|
|
||||
| POST | `/auth/email-codes` | `{email, purpose:"registration"|"login", captcha_token}` -> `{"code":"ok","data":{"retry_after_seconds":60}}`; 60 s throttle per address |
|
||||
| POST | `/auth/local/register` | `{email, code, notification:false}` -> `{created:true,user:{id,email,nickname}}`; 409 `email-exists` if taken |
|
||||
| POST | `/auth/local/login` | `{email, code}` -> same shape, sets cookie `token` |
|
||||
| POST | `/auth/logout` | |
|
||||
| GET | `/auth/google` | 302 -> accounts.google.com (`redirect_uri=/oauth-callback/google`, client_id `376662729962-6p89qbb0nd7e2vqr2da3jd7315mbnvdn`) |
|
||||
| POST | `/auth/dingtalk/sso`, `/auth/dingtalk/consent` | CN/DingTalk entry |
|
||||
| POST | `/auth/qr-login/transactions` | QR login (returns tx id, polls state) |
|
||||
| POST | `/auth/oauth/login-request-url` | 400 without proper shape |
|
||||
| POST | `/auth/oauth/accept-login`, `/accept-consent`, `/consent-check` | OAuth consent dance |
|
||||
|
||||
Captcha: Aliyun Captcha v3. `captcha_token` = **JSON string** of the 2captcha solution object
|
||||
`{sceneId, certifyId, deviceToken, data}`. Object -> 400; `data` only -> 403 `human verification failed`.
|
||||
|
||||
## User
|
||||
|
||||
| method | path | notes |
|
||||
|---|---|---|
|
||||
| GET | `/user/info` | id, email, nickname, is_verified, language, page.month_requests (100000), month_traffic (5 GB) |
|
||||
| GET | `/user/plans` | plan catalog: `subscription-sgp-free` ($0, daily_trial_credits 200, starter_credits 500), plus 2000 / pro 4000 / enterprise 3000-4500 |
|
||||
| GET | `/user/v2/quota` | `{total, used, remaining, exceeded}` — `remaining` respects the hold |
|
||||
| GET | `/user/v2/registration-benefits` | `starter_credit.eligible`, `daily_credit.eligible_now/eligible_from` |
|
||||
| GET | `/user/wallets` | `active_wallets.total`, `daily_credits`, `longterm_credits`, `monthly_credits` |
|
||||
| GET | `/user/billings?limit=N` | ledger: `{type: Bonus|Chat|Blocked, amount, detail:{title}, session_id, created_at}` |
|
||||
| GET | `/user/billings/sessions/{sid}` | per-session charge, e.g. `0.0442` credit |
|
||||
| GET | `/user/v2/personal-subscription-options` | `user_segment:NEW`, purchasable plans |
|
||||
| GET | `/user/v2/personal-subscription-prices` | `free` purchasable:false, prices in cents |
|
||||
| POST | `/user/v2/account-settings` | `{nickname, nation}` (onboarding, optional) |
|
||||
| POST | `/user/v2/redeem` | `{code}` — redeem endpoint alive, no codes known |
|
||||
| POST | `/user/v2/bind-account/create/aliyun` | header `Idempotency-Key: uuid4` -> `{success:true, uid, binding_state:"authorized"}` (no SMS) |
|
||||
| GET | `/user/v2/bind-account/state/aliyun`, `/profile-status/aliyun`, `/accounts/aliyun` | binding state |
|
||||
| GET | `/user/v2/account-context` | |
|
||||
|
||||
## Chat (the real inference path)
|
||||
|
||||
```
|
||||
POST /api/chat-sessions
|
||||
{
|
||||
"agent_id": "7270e986-63e5-3c79-aeca-ffbd92bdef83",
|
||||
"initial_prompt": {"text": "..."},
|
||||
"mode": "flash" | "advanced" | "pro" | "qwen3.8-flash" | "glm-5.3" | ... ,
|
||||
"extra_data": {"user_language": "en-US"},
|
||||
"channel": "qwenwork_web"
|
||||
}
|
||||
-> 201 {"id": "<session>", "first_turn_id": "<turn>", ...}
|
||||
-> 402 {"code":"INSUFFICIENT_RESOURCES","message":"Insufficient credits to start a session"}
|
||||
```
|
||||
|
||||
```
|
||||
GET /api/chat-sessions/{sid}/events?after={seq}
|
||||
-> {"items":[
|
||||
{"type":"method","method":"session","sub_type":"prompt"},
|
||||
{"type":"method","method":"session","sub_type":"agent_thought_chunk",
|
||||
"raw":{"params":{"update":{"content":{"text":"..."}},"_meta":{"seq_id":2}}}},
|
||||
{"type":"method","method":"session","sub_type":"agent_message_chunk",
|
||||
"raw":{"params":{"update":{"content":{"text":"PONG","type":"text"}}}}},
|
||||
{"type":"result","sub_type":"prompt_response"}
|
||||
]}
|
||||
```
|
||||
|
||||
`after` is the last seen `raw.params._meta.seq_id`. Answer text lives only in
|
||||
`agent_message_chunk`; `result/prompt_response` means finished but carries no text.
|
||||
|
||||
```
|
||||
GET /api/chat-sessions/{sid} session object (end_time stays null over REST)
|
||||
PATCH /api/chat-sessions/{sid} update (name/...); 422 on unknown fields
|
||||
DELETE /api/chat-sessions/{sid} "Session deleted successfully"
|
||||
GET /api/chat-sessions/recent?limit=N list
|
||||
GET /api/chat-sessions/{sid}/children
|
||||
GET /api/chat-modes, /api/desktop/chat-modes model catalog (11 entries)
|
||||
GET /api/m/v1/chat-sessions/{sid}[/events] mobile mirror of the same API
|
||||
POST /api/v1/sidebar/order sidebar reorder
|
||||
PATCH /api/v1/chat-sessions/{id}/archive {archived_at}
|
||||
```
|
||||
|
||||
WebSockets: `/api/chat-ws` (protobuf session management — the lifecycle that releases the credit
|
||||
hold), `/api/notify-ws` (jsonrpc), `/ws`.
|
||||
|
||||
### Credit accounting
|
||||
|
||||
Every turn writes `Chat` (negative, e.g. `-0.0164`) plus, when the session is not finished by the
|
||||
WS protocol, a single `Blocked` entry equal to **the entire remaining balance**:
|
||||
|
||||
```
|
||||
Blocked -699.8323 Credits blocked
|
||||
Chat -0.0164 "Reply With PROD OK" granularity:turn
|
||||
```
|
||||
|
||||
`Blocked` is not released by `DELETE`/`PATCH`/`PUT`/`stop`/`cancel`. Accounts that took it stay at
|
||||
`remaining 0, exceeded true` and return 402 on the next `POST /api/chat-sessions`.
|
||||
|
||||
## Business / enterprise extras
|
||||
|
||||
`/biz/signin` (separate login page), `/biz/enterprise/v1/plans`, `/biz/user/v1/skill-hub/*`
|
||||
(connectors, expert kits, my-skills, installs), `/ecommerce/api/v1/*` (reference kits, dashboards,
|
||||
brand profile), `/api/barn/v1/*`, `/api/v1/scheduler`, `/api/sessions/unread|remote-read|remote-unread`.
|
||||
|
||||
## Not working / closed
|
||||
|
||||
- `/api/v1/chat/completions` and every OpenAI-style path on the web host: 401 / 404.
|
||||
- `qwenwork.cn`: `/auth/email-codes` -> 404 (email login disabled), CN entry via Alibaba fast-auth.
|
||||
- Free plan (`subscription-sgp-free`) has `purchasable:false`; no REST route activates its credits.
|
||||
- `/api/marketing/campaigns` -> 404.
|
||||
@@ -0,0 +1,227 @@
|
||||
"""QwenWork autoreg / login over plain HTTP (no browser).
|
||||
|
||||
Flow:
|
||||
1. Aliyun Captcha v3 solved via 2captcha (AlibabaTaskProxyless) -> captcha_token JSON string
|
||||
2. POST /auth/email-codes {email, purpose, captcha_token}
|
||||
3. read 6-digit code from the mailbox (IMAP)
|
||||
4. POST /auth/local/register {email, code, notification:false} (or /auth/local/login)
|
||||
5. JWT arrives as cookie `token`
|
||||
|
||||
Usage:
|
||||
python farm.py user+1@gmail.com --register
|
||||
python farm.py user+1@gmail.com --login
|
||||
|
||||
Env:
|
||||
QW_2CAP path to file with 2captcha key (default ~/.2cap_key)
|
||||
QW_OUT path to accounts jsonl (default ./accounts.jsonl)
|
||||
QW_GMAIL mailbox login
|
||||
QW_GMAIL_PASS mailbox app password
|
||||
QW_IMAP_HOST default imap.gmail.com
|
||||
QW_BASE default https://qwenwork.ai
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import imaplib
|
||||
import email as emaillib
|
||||
import email.utils
|
||||
import http.cookiejar
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
BASE = os.environ.get("QW_BASE", "https://qwenwork.ai")
|
||||
KEY_FILE = os.environ.get("QW_2CAP", os.path.expanduser("~/.2cap_key"))
|
||||
OUT = os.environ.get("QW_OUT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "accounts.jsonl"))
|
||||
USED = os.path.join(os.path.dirname(os.path.abspath(__file__)), "used_codes.txt")
|
||||
GMAIL_USER = os.environ.get("QW_GMAIL", "")
|
||||
GMAIL_APP = os.environ.get("QW_GMAIL_PASS", "")
|
||||
IMAP_HOST = os.environ.get("QW_IMAP_HOST", "imap.gmail.com")
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
|
||||
SCENE, PREFIX, REGION = "l47rwlyt", "13n1x6", "ga"
|
||||
CAPTCHA_LIB = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js?t=2035"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- captcha
|
||||
def solve_captcha():
|
||||
key = open(KEY_FILE).read().strip()
|
||||
task = {
|
||||
"type": "AlibabaTaskProxyless",
|
||||
"websiteUrl": BASE + "/biz/signin",
|
||||
"sceneId": SCENE,
|
||||
"prefix": PREFIX,
|
||||
"region": REGION,
|
||||
"apiGetLib": CAPTCHA_LIB,
|
||||
"userAgent": UA,
|
||||
}
|
||||
req = urllib.request.Request(
|
||||
"https://api.2captcha.com/createTask",
|
||||
data=json.dumps({"clientKey": key, "task": task}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=40) as r:
|
||||
d = json.loads(r.read().decode())
|
||||
if d.get("errorId"):
|
||||
raise RuntimeError("createTask: %s" % d)
|
||||
tid = d["taskId"]
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 300:
|
||||
time.sleep(5)
|
||||
req = urllib.request.Request(
|
||||
"https://api.2captcha.com/getTaskResult",
|
||||
data=json.dumps({"clientKey": key, "taskId": tid}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=40) as r:
|
||||
s = json.loads(r.read().decode())
|
||||
if s.get("errorId"):
|
||||
raise RuntimeError("getTaskResult: %s" % s)
|
||||
if s.get("status") == "ready":
|
||||
# server expects the WHOLE solution object as a JSON *string*
|
||||
return json.dumps(s["solution"], ensure_ascii=False)
|
||||
raise RuntimeError("captcha timeout")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- mailbox
|
||||
def _used():
|
||||
if not os.path.exists(USED):
|
||||
return set()
|
||||
return {l.strip() for l in open(USED, encoding="utf-8") if l.strip()}
|
||||
|
||||
|
||||
def _mark(code):
|
||||
with open(USED, "a", encoding="utf-8") as f:
|
||||
f.write(code + "\n")
|
||||
|
||||
|
||||
def mail_code(t_start, tries=24, delay=5):
|
||||
"""Newest unused 6-digit code from a qwenwork mail received after t_start."""
|
||||
used = _used()
|
||||
for _ in range(tries):
|
||||
time.sleep(delay)
|
||||
try:
|
||||
m = imaplib.IMAP4_SSL(IMAP_HOST, 993)
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
m.login(GMAIL_USER, GMAIL_APP)
|
||||
m.select("INBOX")
|
||||
typ, data = m.search(None, "SINCE", time.strftime("%d-%b-%Y"))
|
||||
ids = (data[0] or b"").split()[-30:]
|
||||
for i in reversed(ids):
|
||||
typ, d = m.fetch(i, "(RFC822)")
|
||||
if typ != "OK" or not d or not d[0]:
|
||||
continue
|
||||
msg = emaillib.message_from_bytes(d[0][1])
|
||||
try:
|
||||
dt = email.utils.parsedate_to_datetime(msg.get("Date"))
|
||||
if dt.timestamp() < t_start - 60:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
head = (msg.get("From", "") + " " + msg.get("Subject", "")).lower()
|
||||
body = ""
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() in ("text/plain", "text/html"):
|
||||
try:
|
||||
body += part.get_payload(decode=True).decode(
|
||||
part.get_content_charset() or "utf-8", "replace")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
body = msg.get_payload(decode=True).decode(
|
||||
msg.get_content_charset() or "utf-8", "replace")
|
||||
except Exception:
|
||||
pass
|
||||
if "qwenwork" not in head and "qwenwork" not in body.lower():
|
||||
continue
|
||||
for code in re.findall(r"\b(\d{6})\b", msg.get("Subject", "") + " " + body):
|
||||
if code in used:
|
||||
continue
|
||||
_mark(code)
|
||||
return code
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
m.logout()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return
|
||||
addr = sys.argv[1]
|
||||
mode = "register" if "--register" in sys.argv else "login"
|
||||
cj = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
|
||||
def api(method, path, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(
|
||||
BASE + path, data=data, method=method,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Origin": BASE,
|
||||
"Referer": BASE + "/biz/signin",
|
||||
"User-Agent": UA,
|
||||
"X-Client-Source": "web",
|
||||
"X-Mule-Language": "en",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with op.open(req, timeout=45) as r:
|
||||
return r.status, r.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode()
|
||||
|
||||
t_start = time.time()
|
||||
tok = solve_captcha()
|
||||
print("[1] captcha ok", len(tok), "chars", flush=True)
|
||||
|
||||
st, body = api("POST", "/auth/email-codes", {
|
||||
"email": addr,
|
||||
"purpose": "login" if mode == "login" else "registration",
|
||||
"captcha_token": tok,
|
||||
})
|
||||
print("[2] email-codes", st, body[:180], flush=True)
|
||||
if st != 200:
|
||||
return
|
||||
|
||||
code = mail_code(t_start)
|
||||
if not code:
|
||||
print("[3] no code in mail", flush=True)
|
||||
return
|
||||
print("[3] code", code, flush=True)
|
||||
|
||||
if mode == "register":
|
||||
st, body = api("POST", "/auth/local/register", {"email": addr, "code": code, "notification": False})
|
||||
else:
|
||||
st, body = api("POST", "/auth/local/login", {"email": addr, "code": code})
|
||||
print("[4]", mode, st, body[:260], flush=True)
|
||||
|
||||
jwt = next((c.value for c in cj if c.name == "token"), None)
|
||||
print("[5] jwt_len", len(jwt or ""), flush=True)
|
||||
|
||||
rec = {"email": addr, "jwt": jwt, "mode": mode, "ts": time.time()}
|
||||
with open(OUT, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
|
||||
if jwt:
|
||||
st, q = api("GET", "/user/v2/quota")
|
||||
print("[6] quota", st, q[:120], flush=True)
|
||||
st, b = api("GET", "/user/v2/registration-benefits")
|
||||
print("[7] benefits", st, b[:200], flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
"""QwenWork -> OpenAI compatible shim (stdlib only).
|
||||
|
||||
Endpoints:
|
||||
POST /v1/chat/completions (JSON or SSE stream)
|
||||
GET /v1/models
|
||||
GET /healthz
|
||||
|
||||
Protocol (reverse engineered):
|
||||
POST {base}/api/chat-sessions {agent_id, mode, initial_prompt:{text}, extra_data:{user_language}, channel:"qwenwork_web"}
|
||||
GET {base}/api/chat-sessions/{sid}/events?after=N
|
||||
-> items[]: type=method method=session sub_type=prompt|agent_thought_chunk|agent_message_chunk
|
||||
type=result sub_type=prompt_response
|
||||
DELETE {base}/api/chat-sessions/{sid} close (best effort, does not lift the credit hold)
|
||||
|
||||
Env:
|
||||
QW_POOL path to accounts jsonl {email, jwt} (default ./accounts.jsonl)
|
||||
QW_PORT listen port (default 48981)
|
||||
QW_BASE upstream (default https://qwenwork.ai)
|
||||
QW_AGENT agent id (default: the web agent used by /app)
|
||||
QW_POLL per-turn poll budget in seconds (default 150)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
BASE = os.environ.get("QW_BASE", "https://qwenwork.ai")
|
||||
AGENT_ID = os.environ.get("QW_AGENT", "7270e986-63e5-3c79-aeca-ffbd92bdef83")
|
||||
PORT = int(os.environ.get("QW_PORT", "48981"))
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
POOL_PATH = os.environ.get("QW_POOL", os.path.join(HERE, "accounts.jsonl"))
|
||||
POLL_MAX = float(os.environ.get("QW_POLL", "150"))
|
||||
COOLDOWN = int(os.environ.get("QW_COOL", "900")) # seconds an account is skipped after 402
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
|
||||
|
||||
# iishko model name -> qwenwork chat mode
|
||||
MODES = {
|
||||
"qw-flash": "flash",
|
||||
"qw-standard": "flash",
|
||||
"qw-pro": "advanced",
|
||||
"qw-advanced": "advanced",
|
||||
"qw-flagship": "pro",
|
||||
"qw-qwen4-max": "qwen4-max",
|
||||
"qw-qwen3.8-max": "qwen3.8-max",
|
||||
"qw-qwen3.8-flash": "qwen3.8-flash",
|
||||
"qw-deepseek-v4.1-flash": "deepseek-flash",
|
||||
"qw-glm-5.3": "glm-5.3",
|
||||
"qw-glm-5.3-flash": "glm-5.3-flash",
|
||||
"qw-kimi-k3.1-pro": "kimi-k3.1-pro",
|
||||
"qw-minimax-m3.1-flash": "minimax-m3.1-flash",
|
||||
}
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cursor = [0]
|
||||
_accounts = []
|
||||
_cool = {} # email -> unix ts until which the account is skipped
|
||||
|
||||
|
||||
class QWError(Exception):
|
||||
def __init__(self, code, msg):
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
super().__init__("%s: %s" % (code, msg))
|
||||
|
||||
|
||||
def load_pool():
|
||||
global _accounts
|
||||
acc = []
|
||||
if os.path.exists(POOL_PATH):
|
||||
for line in open(POOL_PATH, encoding="utf-8"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
d = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
if d.get("jwt"):
|
||||
acc.append(d)
|
||||
_accounts = acc
|
||||
return len(acc)
|
||||
|
||||
|
||||
def pick(skip=None):
|
||||
with _lock:
|
||||
n = len(_accounts)
|
||||
if not n:
|
||||
return None
|
||||
now = time.time()
|
||||
for i in range(n):
|
||||
a = _accounts[(_cursor[0] + i) % n]
|
||||
if skip and a["email"] in skip:
|
||||
continue
|
||||
if _cool.get(a["email"], 0) > now:
|
||||
continue
|
||||
_cursor[0] = (_cursor[0] + i + 1) % n
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def hdrs(jwt):
|
||||
return {
|
||||
"Authorization": "Bearer " + jwt,
|
||||
"User-Agent": UA,
|
||||
"Origin": BASE,
|
||||
"Referer": BASE + "/app/",
|
||||
"Content-Type": "application/json",
|
||||
"X-Client-Source": "web",
|
||||
"X-Mule-Language": "en-US",
|
||||
}
|
||||
|
||||
|
||||
def normalize(messages):
|
||||
parts = []
|
||||
for m in messages or []:
|
||||
c = m.get("content")
|
||||
if isinstance(c, list):
|
||||
c = "".join(x.get("text", "") for x in c if isinstance(x, dict))
|
||||
c = (c or "").strip()
|
||||
if not c:
|
||||
continue
|
||||
role = m.get("role", "user")
|
||||
parts.append(("[%s] " % role) + c if role in ("system", "assistant") else c)
|
||||
return "\n\n".join(parts).strip()
|
||||
|
||||
|
||||
def create_session(jwt, mode, text):
|
||||
body = {
|
||||
"agent_id": AGENT_ID,
|
||||
"initial_prompt": {"text": text},
|
||||
"mode": mode,
|
||||
"extra_data": {"user_language": "en-US"},
|
||||
"channel": "qwenwork_web",
|
||||
}
|
||||
req = urllib.request.Request(BASE + "/api/chat-sessions",
|
||||
data=json.dumps(body).encode(), method="POST", headers=hdrs(jwt))
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
raise QWError(e.code, e.read().decode("utf-8", "replace")[:300])
|
||||
|
||||
|
||||
def events(jwt, sid, after):
|
||||
req = urllib.request.Request("%s/api/chat-sessions/%s/events?after=%d" % (BASE, sid, after),
|
||||
headers=hdrs(jwt))
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
raise QWError(e.code, e.read().decode("utf-8", "replace")[:200])
|
||||
|
||||
|
||||
def close_session(jwt, sid):
|
||||
try:
|
||||
req = urllib.request.Request("%s/api/chat-sessions/%s" % (BASE, sid),
|
||||
method="DELETE", headers=hdrs(jwt))
|
||||
urllib.request.urlopen(req, timeout=20).read()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_turn(jwt, mode, text):
|
||||
"""Return (answer, reasoning, sid). Waits for real agent_message_chunk, not just result."""
|
||||
d = create_session(jwt, mode, text)
|
||||
sid = d.get("id")
|
||||
answer, thought, seq = [], [], 0
|
||||
t0 = time.time()
|
||||
last = [0.0]
|
||||
done = False
|
||||
while time.time() - t0 < POLL_MAX:
|
||||
ev = events(jwt, sid, seq)
|
||||
items = ev.get("items") or []
|
||||
idle = time.time() - last[0]
|
||||
for it in items:
|
||||
params = (it.get("raw") or {}).get("params") or {}
|
||||
meta = params.get("_meta") or {}
|
||||
if isinstance(meta.get("seq_id"), int):
|
||||
seq = max(seq, meta["seq_id"])
|
||||
sub = it.get("sub_type") or ""
|
||||
content = (params.get("update") or {}).get("content") or {}
|
||||
txt = content.get("text") if isinstance(content, dict) else None
|
||||
if sub == "agent_message_chunk" and txt:
|
||||
answer.append(txt)
|
||||
last[0] = time.time()
|
||||
elif sub == "agent_thought_chunk" and txt:
|
||||
thought.append(txt)
|
||||
last[0] = time.time()
|
||||
elif it.get("type") == "result":
|
||||
done = True
|
||||
if done and answer:
|
||||
break
|
||||
if done and not answer and idle > 12:
|
||||
break # result without text -> upstream refused silently
|
||||
time.sleep(0.4 if items else 0.8)
|
||||
close_session(jwt, sid)
|
||||
return "".join(answer), "".join(thought), sid
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, format, *args):
|
||||
sys.stderr.write("[qw] " + (format % args) + "\n")
|
||||
|
||||
def _json(self, code, obj):
|
||||
b = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(b)))
|
||||
self.end_headers()
|
||||
self.wfile.write(b)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/healthz"):
|
||||
return self._json(200, {"ok": True, "accounts": len(_accounts), "models": len(MODES),
|
||||
"cooling": len([1 for v in _cool.values() if v > time.time()])})
|
||||
if self.path.startswith("/v1/models"):
|
||||
return self._json(200, {"object": "list", "data": [
|
||||
{"id": k, "object": "model", "owned_by": "qwenwork"} for k in MODES]})
|
||||
return self._json(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
if not self.path.startswith("/v1/chat/completions"):
|
||||
return self._json(404, {"error": "not found"})
|
||||
try:
|
||||
ln = int(self.headers.get("Content-Length") or 0)
|
||||
req = json.loads(self.rfile.read(ln) or b"{}")
|
||||
except Exception:
|
||||
return self._json(400, {"error": {"message": "bad json"}})
|
||||
|
||||
model = req.get("model") or "qw-flash"
|
||||
mode = MODES.get(model)
|
||||
if not mode:
|
||||
return self._json(404, {"error": {"message": "model %s not found" % model,
|
||||
"type": "invalid_request_error"}})
|
||||
text = normalize(req.get("messages"))
|
||||
if not text:
|
||||
return self._json(400, {"error": {"message": "empty prompt"}})
|
||||
stream = bool(req.get("stream"))
|
||||
|
||||
acc = pick()
|
||||
if not acc:
|
||||
return self._json(503, {"error": {"message": "no qwenwork account available "
|
||||
"(pool empty or all cooling)"}})
|
||||
tried, ans, sid, last_err = set(), None, None, None
|
||||
for _ in range(min(4, max(1, len(_accounts)))):
|
||||
try:
|
||||
ans, _thought, sid = run_turn(acc["jwt"], mode, text)
|
||||
if ans:
|
||||
last_err = None
|
||||
break
|
||||
last_err = QWError(502, "empty answer (session created but no text)")
|
||||
except QWError as e:
|
||||
last_err = e
|
||||
tried.add(acc["email"])
|
||||
if last_err.code in (401, 402, 403):
|
||||
_cool[acc["email"]] = time.time() + COOLDOWN
|
||||
acc = pick(skip=tried)
|
||||
if not acc:
|
||||
break
|
||||
|
||||
if ans is None:
|
||||
code = last_err.code if last_err and isinstance(last_err.code, int) else 502
|
||||
return self._json(code, {"error": {"message": (last_err.msg if last_err else "upstream failed"),
|
||||
"type": "upstream_error"}})
|
||||
ans = ans or ""
|
||||
|
||||
tid = "chatcmpl-" + uuid.uuid4().hex[:24]
|
||||
created = int(time.time())
|
||||
if not stream:
|
||||
return self._json(200, {
|
||||
"id": tid, "object": "chat.completion", "created": created, "model": model,
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": ans},
|
||||
"finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": max(1, len(text) // 4),
|
||||
"completion_tokens": max(1, len(ans) // 4),
|
||||
"total_tokens": max(1, (len(text) + len(ans)) // 4)},
|
||||
"x_qwenwork_session": sid,
|
||||
})
|
||||
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.send_header("Connection", "keep-alive")
|
||||
self.end_headers()
|
||||
|
||||
def chunk(delta, finish=None):
|
||||
payload = {"id": tid, "object": "chat.completion.chunk", "created": created, "model": model,
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
|
||||
self.wfile.write(("data: " + json.dumps(payload, ensure_ascii=False) + "\n\n").encode())
|
||||
self.wfile.flush()
|
||||
|
||||
try:
|
||||
chunk({"role": "assistant", "content": ""})
|
||||
step = 60
|
||||
for i in range(0, len(ans), step):
|
||||
chunk({"content": ans[i:i + step]})
|
||||
chunk({}, "stop")
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
n = load_pool()
|
||||
print("[qw] pool=%d port=%d base=%s" % (n, PORT, BASE), flush=True)
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H)
|
||||
srv.daemon_threads = True
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user