qwenproxy-cli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +14 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +78 -78
  5. package/src/api/error-classifier.ts +159 -159
  6. package/src/api/error-helpers.ts +118 -118
  7. package/src/api/models.ts +261 -261
  8. package/src/api/server.ts +860 -859
  9. package/src/cache/memory-cache.ts +385 -385
  10. package/src/clean-cache.ts +204 -204
  11. package/src/core/account-concurrency.ts +671 -671
  12. package/src/core/account-manager.ts +301 -297
  13. package/src/core/account-priority.ts +163 -163
  14. package/src/core/accounts.ts +186 -186
  15. package/src/core/config.ts +383 -383
  16. package/src/core/crypto-utils.ts +79 -79
  17. package/src/core/database.ts +276 -276
  18. package/src/core/errors.ts +118 -118
  19. package/src/core/logger.ts +269 -269
  20. package/src/core/memory-usage.ts +84 -84
  21. package/src/core/metrics.ts +291 -291
  22. package/src/core/model-alias.ts +77 -77
  23. package/src/core/model-registry.ts +544 -544
  24. package/src/core/mutex.ts +119 -119
  25. package/src/core/paths.ts +199 -199
  26. package/src/core/prompt-limits.ts +214 -214
  27. package/src/core/reasoning-effort.ts +102 -102
  28. package/src/core/stream-registry.ts +96 -96
  29. package/src/core/waf-isolation.ts +117 -117
  30. package/src/core/watchdog.ts +195 -195
  31. package/src/delete-chats.ts +23 -23
  32. package/src/index.ts +65 -64
  33. package/src/login.ts +147 -147
  34. package/src/reset-cooldowns.ts +11 -11
  35. package/src/routes/anthropic/index.ts +355 -355
  36. package/src/routes/anthropic/translate.ts +522 -522
  37. package/src/routes/anthropic/types.ts +154 -154
  38. package/src/routes/anthropic/validation.ts +144 -144
  39. package/src/routes/chat/account.ts +1817 -1817
  40. package/src/routes/chat/context.ts +241 -241
  41. package/src/routes/chat/errors.ts +85 -85
  42. package/src/routes/chat/helpers.ts +268 -268
  43. package/src/routes/chat/index.ts +618 -618
  44. package/src/routes/chat/media.ts +285 -285
  45. package/src/routes/chat/retry-policy.ts +754 -754
  46. package/src/routes/chat/stop.ts +98 -98
  47. package/src/routes/chat/streaming.ts +2710 -2710
  48. package/src/routes/chat/validation.ts +526 -526
  49. package/src/routes/chat.ts +2 -2
  50. package/src/routes/completions.ts +290 -290
  51. package/src/routes/images.ts +139 -139
  52. package/src/routes/responses/adapter.ts +503 -503
  53. package/src/routes/responses/index.ts +405 -405
  54. package/src/routes/responses/state.ts +230 -230
  55. package/src/routes/responses/streaming.ts +528 -528
  56. package/src/routes/responses/types.ts +285 -285
  57. package/src/routes/responses/validation.ts +202 -202
  58. package/src/routes/upload.ts +731 -731
  59. package/src/routes/videos.ts +214 -214
  60. package/src/services/auth-playwright.ts +173 -173
  61. package/src/services/captcha-coordinator.ts +161 -161
  62. package/src/services/captcha-solver.ts +553 -553
  63. package/src/services/chat-cleanup.ts +80 -80
  64. package/src/services/context-meter.ts +317 -317
  65. package/src/services/fingerprint.ts +242 -242
  66. package/src/services/human-behavior.ts +173 -173
  67. package/src/services/media-generation.ts +1748 -1748
  68. package/src/services/playwright.ts +2800 -2800
  69. package/src/services/qwen-chat-pool.ts +345 -345
  70. package/src/services/qwen-errors.ts +133 -133
  71. package/src/services/qwen-headers.ts +79 -79
  72. package/src/services/qwen-thread-state.ts +393 -393
  73. package/src/services/qwen-url.ts +19 -19
  74. package/src/services/qwen.ts +3126 -3126
  75. package/src/services/session-keeper.ts +88 -88
  76. package/src/services/token-estimation-metrics.ts +118 -118
  77. package/src/sync/claude-code.ts +75 -75
  78. package/src/sync/codex.ts +123 -123
  79. package/src/sync/index.ts +362 -362
  80. package/src/sync/omp.ts +105 -105
  81. package/src/sync/opencode.ts +214 -214
  82. package/src/sync/types.ts +53 -53
  83. package/src/sync/utils.ts +27 -27
  84. package/src/sync-clients.ts +189 -189
  85. package/src/tools/instructions.ts +137 -137
  86. package/src/tools/manifest.ts +81 -81
  87. package/src/tools/parser.ts +2989 -2989
  88. package/src/tools/toolcall-tags.ts +142 -142
  89. package/src/tui/app.ts +264 -264
  90. package/src/tui/index.ts +61 -61
  91. package/src/tui/markdown.ts +258 -258
  92. package/src/tui/proxy-client.ts +331 -326
  93. package/src/tui/screen.ts +294 -278
  94. package/src/tui/server-manager.ts +270 -270
  95. package/src/tui/theme.ts +432 -432
  96. package/src/tui/types.ts +33 -33
  97. package/src/tui/views/accounts-view.ts +656 -656
  98. package/src/tui/views/chat-view.ts +1018 -823
  99. package/src/tui/views/logs-view.ts +479 -413
  100. package/src/tui/views/status-view.ts +204 -204
  101. package/src/tui/views/storage-view.ts +304 -291
  102. package/src/tui/views/sync-view.ts +409 -409
  103. package/src/types/ali-oss.d.ts +32 -32
  104. package/src/utils/context-truncation.ts +84 -84
  105. package/src/utils/json.ts +380 -380
  106. package/src/utils/session-id.ts +37 -37
  107. package/src/utils/tool-call-guard.ts +84 -84
  108. package/src/utils/types.ts +109 -109
@@ -1,173 +1,173 @@
1
- import { AuthError } from "../core/errors.ts";
2
- import { getAccountCredentials, loadAccounts } from "../core/accounts.ts";
3
- import { config } from "../core/config.ts";
4
- import {
5
- getBasicHeaders as getPlaywrightBasicHeaders,
6
- initPlaywrightForAccount,
7
- isPlaywrightInitialized,
8
- refreshHeaders,
9
- } from "./playwright.ts";
10
-
11
- export interface HeaderResult {
12
- headers: Record<string, string>;
13
- chatSessionId: string;
14
- parentMessageId: string | null;
15
- }
16
-
17
- export function isAuthMockEnabled(): boolean {
18
- return (
19
- process.env.TEST_MOCK_QWEN_AUTH === "true" &&
20
- process.env.NODE_ENV !== "production"
21
- );
22
- }
23
-
24
- function isRunningUnderNodeTest(): boolean {
25
- return process.argv.some(
26
- (arg) =>
27
- arg === "--test" ||
28
- arg.includes("src/tests/") ||
29
- arg.includes("src\\tests\\"),
30
- );
31
- }
32
-
33
- async function ensurePlaywrightInitialized(accountId: string): Promise<void> {
34
- if (isPlaywrightInitialized(accountId)) return;
35
-
36
- if (isRunningUnderNodeTest()) {
37
- throw new Error(`Playwright not initialized for account: ${accountId}`);
38
- }
39
-
40
- const credentials = getAccountCredentials(accountId);
41
- if (!credentials) {
42
- throw new AuthError(`Qwen account ${accountId} is not configured.`);
43
- }
44
-
45
- await initPlaywrightForAccount(
46
- credentials,
47
- config.playwright.headless,
48
- config.playwright.browser,
49
- );
50
-
51
- // Standby accounts are initialized lazily. Apply the same account-level
52
- // settings that startup preparation would apply.
53
- try {
54
- const { disableNativeTools } = await import("./qwen.ts");
55
- await disableNativeTools(accountId).catch(() => {});
56
- } catch {
57
- // Non-fatal: chat creation will still work with default account settings.
58
- }
59
- }
60
-
61
- export async function getBasicHeaders(accountId?: string): Promise<{
62
- cookie: string;
63
- userAgent: string;
64
- bxV: string;
65
- bxUa: string;
66
- bxUmidtoken: string;
67
- secChUa: string;
68
- secChUaMobile: string;
69
- secChUaPlatform: string;
70
- version: string;
71
- }> {
72
- if (isAuthMockEnabled()) {
73
- return {
74
- cookie: "token=mock",
75
- userAgent: "mock",
76
- bxV: "2.5.37",
77
- bxUa: "mock-bx-ua",
78
- bxUmidtoken: "mock-bx-umidtoken",
79
- secChUa: "",
80
- secChUaMobile: "?0",
81
- secChUaPlatform: "",
82
- version: "0.2.89",
83
- };
84
- }
85
-
86
- const resolvedAccountId = accountId ?? loadAccounts()[0]?.id;
87
- if (!resolvedAccountId) {
88
- throw new AuthError(
89
- "No Qwen accounts configured. Add accounts with npm run login.",
90
- );
91
- }
92
-
93
- await ensurePlaywrightInitialized(resolvedAccountId);
94
- return getPlaywrightBasicHeaders(resolvedAccountId);
95
- }
96
-
97
- export function isTokenExpiringSoon(
98
- cookie: string,
99
- minutesBeforeExpiry = 5,
100
- ): boolean {
101
- const tokenMatch = cookie.match(/token=([^;]+)/);
102
- if (!tokenMatch) return false;
103
-
104
- try {
105
- const token = decodeURIComponent(tokenMatch[1]);
106
- const segments = token.split(".");
107
- // Some Qwen deployments use opaque cookies. Treating those as expired
108
- // forces expensive header capture on every personalization request.
109
- if (segments.length !== 3 || !segments[1]) return false;
110
-
111
- const payloadJson = Buffer.from(segments[1], "base64url").toString("utf-8");
112
- const payload = JSON.parse(payloadJson);
113
- const exp = payload.exp;
114
- if (typeof exp !== "number" || !Number.isFinite(exp)) return false;
115
-
116
- const nowSec = Math.floor(Date.now() / 1000);
117
- const thresholdSec = minutesBeforeExpiry * 60;
118
- return exp - nowSec < thresholdSec;
119
- } catch {
120
- return false;
121
- }
122
- }
123
-
124
- export async function getQwenHeaders(
125
- forceNew = false,
126
- accountId?: string,
127
- ): Promise<HeaderResult> {
128
- if (isAuthMockEnabled()) {
129
- const basic = await getBasicHeaders(accountId);
130
- return {
131
- headers: {
132
- cookie: basic.cookie,
133
- "user-agent": basic.userAgent,
134
- "bx-v": basic.bxV,
135
- "bx-ua": basic.bxUa,
136
- "bx-umidtoken": basic.bxUmidtoken,
137
- version: basic.version,
138
- },
139
- chatSessionId: "",
140
- parentMessageId: null,
141
- };
142
- }
143
-
144
- const resolvedAccountId = accountId ?? loadAccounts()[0]?.id;
145
- if (!resolvedAccountId) {
146
- throw new AuthError(
147
- "No Qwen accounts configured. Add accounts with npm run login.",
148
- );
149
- }
150
-
151
- await ensurePlaywrightInitialized(resolvedAccountId);
152
-
153
- if (forceNew) {
154
- await refreshHeaders(resolvedAccountId);
155
- }
156
-
157
- const basic = await getPlaywrightBasicHeaders(resolvedAccountId);
158
- return {
159
- headers: {
160
- cookie: basic.cookie,
161
- "user-agent": basic.userAgent,
162
- "bx-v": basic.bxV,
163
- "bx-ua": basic.bxUa || "",
164
- "bx-umidtoken": basic.bxUmidtoken || "",
165
- "sec-ch-ua": basic.secChUa,
166
- "sec-ch-ua-mobile": basic.secChUaMobile,
167
- "sec-ch-ua-platform": basic.secChUaPlatform,
168
- version: basic.version,
169
- },
170
- chatSessionId: "",
171
- parentMessageId: null,
172
- };
173
- }
1
+ import { AuthError } from "../core/errors.ts";
2
+ import { getAccountCredentials, loadAccounts } from "../core/accounts.ts";
3
+ import { config } from "../core/config.ts";
4
+ import {
5
+ getBasicHeaders as getPlaywrightBasicHeaders,
6
+ initPlaywrightForAccount,
7
+ isPlaywrightInitialized,
8
+ refreshHeaders,
9
+ } from "./playwright.ts";
10
+
11
+ export interface HeaderResult {
12
+ headers: Record<string, string>;
13
+ chatSessionId: string;
14
+ parentMessageId: string | null;
15
+ }
16
+
17
+ export function isAuthMockEnabled(): boolean {
18
+ return (
19
+ process.env.TEST_MOCK_QWEN_AUTH === "true" &&
20
+ process.env.NODE_ENV !== "production"
21
+ );
22
+ }
23
+
24
+ function isRunningUnderNodeTest(): boolean {
25
+ return process.argv.some(
26
+ (arg) =>
27
+ arg === "--test" ||
28
+ arg.includes("src/tests/") ||
29
+ arg.includes("src\\tests\\"),
30
+ );
31
+ }
32
+
33
+ async function ensurePlaywrightInitialized(accountId: string): Promise<void> {
34
+ if (isPlaywrightInitialized(accountId)) return;
35
+
36
+ if (isRunningUnderNodeTest()) {
37
+ throw new Error(`Playwright not initialized for account: ${accountId}`);
38
+ }
39
+
40
+ const credentials = getAccountCredentials(accountId);
41
+ if (!credentials) {
42
+ throw new AuthError(`Qwen account ${accountId} is not configured.`);
43
+ }
44
+
45
+ await initPlaywrightForAccount(
46
+ credentials,
47
+ config.playwright.headless,
48
+ config.playwright.browser,
49
+ );
50
+
51
+ // Standby accounts are initialized lazily. Apply the same account-level
52
+ // settings that startup preparation would apply.
53
+ try {
54
+ const { disableNativeTools } = await import("./qwen.ts");
55
+ await disableNativeTools(accountId).catch(() => {});
56
+ } catch {
57
+ // Non-fatal: chat creation will still work with default account settings.
58
+ }
59
+ }
60
+
61
+ export async function getBasicHeaders(accountId?: string): Promise<{
62
+ cookie: string;
63
+ userAgent: string;
64
+ bxV: string;
65
+ bxUa: string;
66
+ bxUmidtoken: string;
67
+ secChUa: string;
68
+ secChUaMobile: string;
69
+ secChUaPlatform: string;
70
+ version: string;
71
+ }> {
72
+ if (isAuthMockEnabled()) {
73
+ return {
74
+ cookie: "token=mock",
75
+ userAgent: "mock",
76
+ bxV: "2.5.37",
77
+ bxUa: "mock-bx-ua",
78
+ bxUmidtoken: "mock-bx-umidtoken",
79
+ secChUa: "",
80
+ secChUaMobile: "?0",
81
+ secChUaPlatform: "",
82
+ version: "0.2.89",
83
+ };
84
+ }
85
+
86
+ const resolvedAccountId = accountId ?? loadAccounts()[0]?.id;
87
+ if (!resolvedAccountId) {
88
+ throw new AuthError(
89
+ "No Qwen accounts configured. Add accounts with npm run login.",
90
+ );
91
+ }
92
+
93
+ await ensurePlaywrightInitialized(resolvedAccountId);
94
+ return getPlaywrightBasicHeaders(resolvedAccountId);
95
+ }
96
+
97
+ export function isTokenExpiringSoon(
98
+ cookie: string,
99
+ minutesBeforeExpiry = 5,
100
+ ): boolean {
101
+ const tokenMatch = cookie.match(/token=([^;]+)/);
102
+ if (!tokenMatch) return false;
103
+
104
+ try {
105
+ const token = decodeURIComponent(tokenMatch[1]);
106
+ const segments = token.split(".");
107
+ // Some Qwen deployments use opaque cookies. Treating those as expired
108
+ // forces expensive header capture on every personalization request.
109
+ if (segments.length !== 3 || !segments[1]) return false;
110
+
111
+ const payloadJson = Buffer.from(segments[1], "base64url").toString("utf-8");
112
+ const payload = JSON.parse(payloadJson);
113
+ const exp = payload.exp;
114
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return false;
115
+
116
+ const nowSec = Math.floor(Date.now() / 1000);
117
+ const thresholdSec = minutesBeforeExpiry * 60;
118
+ return exp - nowSec < thresholdSec;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ export async function getQwenHeaders(
125
+ forceNew = false,
126
+ accountId?: string,
127
+ ): Promise<HeaderResult> {
128
+ if (isAuthMockEnabled()) {
129
+ const basic = await getBasicHeaders(accountId);
130
+ return {
131
+ headers: {
132
+ cookie: basic.cookie,
133
+ "user-agent": basic.userAgent,
134
+ "bx-v": basic.bxV,
135
+ "bx-ua": basic.bxUa,
136
+ "bx-umidtoken": basic.bxUmidtoken,
137
+ version: basic.version,
138
+ },
139
+ chatSessionId: "",
140
+ parentMessageId: null,
141
+ };
142
+ }
143
+
144
+ const resolvedAccountId = accountId ?? loadAccounts()[0]?.id;
145
+ if (!resolvedAccountId) {
146
+ throw new AuthError(
147
+ "No Qwen accounts configured. Add accounts with npm run login.",
148
+ );
149
+ }
150
+
151
+ await ensurePlaywrightInitialized(resolvedAccountId);
152
+
153
+ if (forceNew) {
154
+ await refreshHeaders(resolvedAccountId);
155
+ }
156
+
157
+ const basic = await getPlaywrightBasicHeaders(resolvedAccountId);
158
+ return {
159
+ headers: {
160
+ cookie: basic.cookie,
161
+ "user-agent": basic.userAgent,
162
+ "bx-v": basic.bxV,
163
+ "bx-ua": basic.bxUa || "",
164
+ "bx-umidtoken": basic.bxUmidtoken || "",
165
+ "sec-ch-ua": basic.secChUa,
166
+ "sec-ch-ua-mobile": basic.secChUaMobile,
167
+ "sec-ch-ua-platform": basic.secChUaPlatform,
168
+ version: basic.version,
169
+ },
170
+ chatSessionId: "",
171
+ parentMessageId: null,
172
+ };
173
+ }
@@ -1,161 +1,161 @@
1
- import type { Page } from "patchright";
2
- import { metrics } from "../core/metrics.ts";
3
- import { config } from "../core/config.ts";
4
- import { withAccountPage } from "./playwright.ts";
5
- import { qwenUrl } from "./qwen-url.ts";
6
- import {
7
- extractBaxiaChallengeUrl,
8
- logBaxiaCaptcha,
9
- sanitizeCaptchaErrorDetail,
10
- solveBaxiaCaptcha,
11
- } from "./captcha-solver.ts";
12
-
13
- const CHALLENGE_NAVIGATION_TIMEOUT_MS = 20_000;
14
- const CHALLENGE_PATH_MARKER = "_____tmd_____";
15
-
16
- /**
17
- * A challenge that could not be solved seconds ago will not be solvable on the
18
- * immediate retry either. Without this window every attempt of the request
19
- * retry loop pays the full solver budget again, which is what turned a single
20
- * unsolved challenge into minutes of dead time.
21
- */
22
- const FAILED_RECOVERY_BACKOFF_MS = 30_000;
23
- const lastFailedRecoveryAt = new Map<string, number>();
24
-
25
- async function gotoBestEffort(page: Page, url: string): Promise<void> {
26
- // A WAF-blocked navigation can time out while still having rendered the
27
- // challenge, so a failure here must not abort the solve attempt.
28
- await page
29
- .goto(url, {
30
- waitUntil: "domcontentloaded",
31
- timeout: Math.min(
32
- config.timeouts.navigation,
33
- CHALLENGE_NAVIGATION_TIMEOUT_MS,
34
- ),
35
- })
36
- .catch(() => undefined);
37
- }
38
-
39
- /**
40
- * Make the challenge visible in the account page and solve it.
41
- *
42
- * Exported so the recovery sequence can be exercised without a live browser.
43
- */
44
- export async function solveChallengeOnPage(
45
- page: Page,
46
- challengeUrl: string | null,
47
- waitForMs = config.captcha.timeoutMs,
48
- ): Promise<boolean> {
49
- const solverOptions = {
50
- maxAttempts: config.captcha.maxAttempts,
51
- retryDelayMs: config.captcha.retryDelayMs,
52
- settleMs: config.captcha.settleMs,
53
- };
54
-
55
- // Qwen's own Baxia SDK sometimes renders the dialog for the background
56
- // fetch. When it did, solve it in place: navigating away would discard the
57
- // challenge the SDK is waiting on.
58
- if (await solveBaxiaCaptcha(page, { ...solverOptions, waitForMs: 0 })) {
59
- return true;
60
- }
61
-
62
- logBaxiaCaptcha(
63
- "challenge_opened",
64
- { source: challengeUrl ? "response_body" : "chat_reload" },
65
- true,
66
- );
67
- await gotoBestEffort(page, challengeUrl ?? qwenUrl("/"));
68
-
69
- try {
70
- return await solveBaxiaCaptcha(page, { ...solverOptions, waitForMs });
71
- } finally {
72
- // Never leave the account page parked on the punish document: a stale
73
- // challenge page makes the next detection pass find itself.
74
- if (page.url().includes(CHALLENGE_PATH_MARKER)) {
75
- await gotoBestEffort(page, qwenUrl("/"));
76
- }
77
- }
78
- }
79
-
80
- /**
81
- * Run the configured first-party challenge adapter without rotating accounts.
82
- * The account page mutex prevents a challenge solve from racing login, header
83
- * capture, settings sync, or another page mutation.
84
- *
85
- * `challengeBody` is the upstream response that was identified as a challenge.
86
- * The completion request runs as a background fetch, so the WAF answers it with
87
- * a punish document that is never rendered; opening that document in the page
88
- * is what gives the solver a slider to drive.
89
- */
90
- export async function recoverBaxiaCaptcha(
91
- accountId: string | undefined,
92
- label: string,
93
- options: { challengeBody?: string } = {},
94
- ): Promise<boolean> {
95
- if (!config.captcha.enabled || !accountId) return false;
96
-
97
- const solver = "baxia";
98
- const startedAt = Date.now();
99
-
100
- const lastFailure = lastFailedRecoveryAt.get(accountId) ?? 0;
101
- if (startedAt - lastFailure < FAILED_RECOVERY_BACKOFF_MS) {
102
- logBaxiaCaptcha("recovery_skipped", { target: label }, true);
103
- return false;
104
- }
105
-
106
- metrics.increment("captcha.challenges.detected", 1, { solver });
107
-
108
- const challengeUrl = options.challengeBody
109
- ? extractBaxiaChallengeUrl(options.challengeBody, config.qwen.baseUrl)
110
- : null;
111
-
112
- // The slider itself waits up to 5s for each attempt. Keep the page
113
- // operation alive for the full bounded solver budget so a slow challenge
114
- // cannot be mistaken for a stuck browser and reset the account context.
115
- // Two navigations (open the challenge, return to the chat page) are part of
116
- // the recovery, so their budget belongs in the same total.
117
- const solverOperationTimeoutMs = Math.max(
118
- config.timeouts.page,
119
- config.captcha.timeoutMs +
120
- config.captcha.maxAttempts *
121
- (5_000 + config.captcha.retryDelayMs + config.captcha.settleMs) +
122
- 2 * CHALLENGE_NAVIGATION_TIMEOUT_MS +
123
- 5_000,
124
- );
125
-
126
- try {
127
- const solved = await withAccountPage(
128
- accountId,
129
- (page) => solveChallengeOnPage(page, challengeUrl),
130
- solverOperationTimeoutMs,
131
- Math.min(config.timeouts.page, 5_000),
132
- );
133
-
134
- metrics.histogram("captcha.solve.duration", Date.now() - startedAt, {
135
- solver,
136
- });
137
-
138
- if (solved) {
139
- lastFailedRecoveryAt.delete(accountId);
140
- metrics.increment("captcha.solves.succeeded", 1, { solver });
141
- logBaxiaCaptcha("recovery_succeeded", { target: label });
142
- return true;
143
- }
144
-
145
- lastFailedRecoveryAt.set(accountId, Date.now());
146
- metrics.increment("captcha.solves.failed", 1, { solver });
147
- logBaxiaCaptcha("recovery_not_solved", { target: label });
148
- return false;
149
- } catch (error) {
150
- lastFailedRecoveryAt.set(accountId, Date.now());
151
- metrics.increment("captcha.solves.failed", 1, { solver });
152
- const errorKind = error instanceof Error ? error.name : "UnknownError";
153
- const detail = sanitizeCaptchaErrorDetail(error);
154
- logBaxiaCaptcha("recovery_failed", {
155
- target: label,
156
- error: errorKind,
157
- detail,
158
- });
159
- return false;
160
- }
161
- }
1
+ import type { Page } from "patchright";
2
+ import { metrics } from "../core/metrics.ts";
3
+ import { config } from "../core/config.ts";
4
+ import { withAccountPage } from "./playwright.ts";
5
+ import { qwenUrl } from "./qwen-url.ts";
6
+ import {
7
+ extractBaxiaChallengeUrl,
8
+ logBaxiaCaptcha,
9
+ sanitizeCaptchaErrorDetail,
10
+ solveBaxiaCaptcha,
11
+ } from "./captcha-solver.ts";
12
+
13
+ const CHALLENGE_NAVIGATION_TIMEOUT_MS = 20_000;
14
+ const CHALLENGE_PATH_MARKER = "_____tmd_____";
15
+
16
+ /**
17
+ * A challenge that could not be solved seconds ago will not be solvable on the
18
+ * immediate retry either. Without this window every attempt of the request
19
+ * retry loop pays the full solver budget again, which is what turned a single
20
+ * unsolved challenge into minutes of dead time.
21
+ */
22
+ const FAILED_RECOVERY_BACKOFF_MS = 30_000;
23
+ const lastFailedRecoveryAt = new Map<string, number>();
24
+
25
+ async function gotoBestEffort(page: Page, url: string): Promise<void> {
26
+ // A WAF-blocked navigation can time out while still having rendered the
27
+ // challenge, so a failure here must not abort the solve attempt.
28
+ await page
29
+ .goto(url, {
30
+ waitUntil: "domcontentloaded",
31
+ timeout: Math.min(
32
+ config.timeouts.navigation,
33
+ CHALLENGE_NAVIGATION_TIMEOUT_MS,
34
+ ),
35
+ })
36
+ .catch(() => undefined);
37
+ }
38
+
39
+ /**
40
+ * Make the challenge visible in the account page and solve it.
41
+ *
42
+ * Exported so the recovery sequence can be exercised without a live browser.
43
+ */
44
+ export async function solveChallengeOnPage(
45
+ page: Page,
46
+ challengeUrl: string | null,
47
+ waitForMs = config.captcha.timeoutMs,
48
+ ): Promise<boolean> {
49
+ const solverOptions = {
50
+ maxAttempts: config.captcha.maxAttempts,
51
+ retryDelayMs: config.captcha.retryDelayMs,
52
+ settleMs: config.captcha.settleMs,
53
+ };
54
+
55
+ // Qwen's own Baxia SDK sometimes renders the dialog for the background
56
+ // fetch. When it did, solve it in place: navigating away would discard the
57
+ // challenge the SDK is waiting on.
58
+ if (await solveBaxiaCaptcha(page, { ...solverOptions, waitForMs: 0 })) {
59
+ return true;
60
+ }
61
+
62
+ logBaxiaCaptcha(
63
+ "challenge_opened",
64
+ { source: challengeUrl ? "response_body" : "chat_reload" },
65
+ true,
66
+ );
67
+ await gotoBestEffort(page, challengeUrl ?? qwenUrl("/"));
68
+
69
+ try {
70
+ return await solveBaxiaCaptcha(page, { ...solverOptions, waitForMs });
71
+ } finally {
72
+ // Never leave the account page parked on the punish document: a stale
73
+ // challenge page makes the next detection pass find itself.
74
+ if (page.url().includes(CHALLENGE_PATH_MARKER)) {
75
+ await gotoBestEffort(page, qwenUrl("/"));
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Run the configured first-party challenge adapter without rotating accounts.
82
+ * The account page mutex prevents a challenge solve from racing login, header
83
+ * capture, settings sync, or another page mutation.
84
+ *
85
+ * `challengeBody` is the upstream response that was identified as a challenge.
86
+ * The completion request runs as a background fetch, so the WAF answers it with
87
+ * a punish document that is never rendered; opening that document in the page
88
+ * is what gives the solver a slider to drive.
89
+ */
90
+ export async function recoverBaxiaCaptcha(
91
+ accountId: string | undefined,
92
+ label: string,
93
+ options: { challengeBody?: string } = {},
94
+ ): Promise<boolean> {
95
+ if (!config.captcha.enabled || !accountId) return false;
96
+
97
+ const solver = "baxia";
98
+ const startedAt = Date.now();
99
+
100
+ const lastFailure = lastFailedRecoveryAt.get(accountId) ?? 0;
101
+ if (startedAt - lastFailure < FAILED_RECOVERY_BACKOFF_MS) {
102
+ logBaxiaCaptcha("recovery_skipped", { target: label }, true);
103
+ return false;
104
+ }
105
+
106
+ metrics.increment("captcha.challenges.detected", 1, { solver });
107
+
108
+ const challengeUrl = options.challengeBody
109
+ ? extractBaxiaChallengeUrl(options.challengeBody, config.qwen.baseUrl)
110
+ : null;
111
+
112
+ // The slider itself waits up to 5s for each attempt. Keep the page
113
+ // operation alive for the full bounded solver budget so a slow challenge
114
+ // cannot be mistaken for a stuck browser and reset the account context.
115
+ // Two navigations (open the challenge, return to the chat page) are part of
116
+ // the recovery, so their budget belongs in the same total.
117
+ const solverOperationTimeoutMs = Math.max(
118
+ config.timeouts.page,
119
+ config.captcha.timeoutMs +
120
+ config.captcha.maxAttempts *
121
+ (5_000 + config.captcha.retryDelayMs + config.captcha.settleMs) +
122
+ 2 * CHALLENGE_NAVIGATION_TIMEOUT_MS +
123
+ 5_000,
124
+ );
125
+
126
+ try {
127
+ const solved = await withAccountPage(
128
+ accountId,
129
+ (page) => solveChallengeOnPage(page, challengeUrl),
130
+ solverOperationTimeoutMs,
131
+ Math.min(config.timeouts.page, 5_000),
132
+ );
133
+
134
+ metrics.histogram("captcha.solve.duration", Date.now() - startedAt, {
135
+ solver,
136
+ });
137
+
138
+ if (solved) {
139
+ lastFailedRecoveryAt.delete(accountId);
140
+ metrics.increment("captcha.solves.succeeded", 1, { solver });
141
+ logBaxiaCaptcha("recovery_succeeded", { target: label });
142
+ return true;
143
+ }
144
+
145
+ lastFailedRecoveryAt.set(accountId, Date.now());
146
+ metrics.increment("captcha.solves.failed", 1, { solver });
147
+ logBaxiaCaptcha("recovery_not_solved", { target: label });
148
+ return false;
149
+ } catch (error) {
150
+ lastFailedRecoveryAt.set(accountId, Date.now());
151
+ metrics.increment("captcha.solves.failed", 1, { solver });
152
+ const errorKind = error instanceof Error ? error.name : "UnknownError";
153
+ const detail = sanitizeCaptchaErrorDetail(error);
154
+ logBaxiaCaptcha("recovery_failed", {
155
+ target: label,
156
+ error: errorKind,
157
+ detail,
158
+ });
159
+ return false;
160
+ }
161
+ }