qwenproxy-cli 1.0.0

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 (109) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +907 -0
  3. package/bin/qwenproxy.js +141 -0
  4. package/package.json +78 -0
  5. package/src/api/error-classifier.ts +159 -0
  6. package/src/api/error-helpers.ts +118 -0
  7. package/src/api/models.ts +261 -0
  8. package/src/api/server.ts +859 -0
  9. package/src/cache/memory-cache.ts +385 -0
  10. package/src/clean-cache.ts +204 -0
  11. package/src/core/account-concurrency.ts +671 -0
  12. package/src/core/account-manager.ts +297 -0
  13. package/src/core/account-priority.ts +163 -0
  14. package/src/core/accounts.ts +186 -0
  15. package/src/core/config.ts +383 -0
  16. package/src/core/crypto-utils.ts +79 -0
  17. package/src/core/database.ts +276 -0
  18. package/src/core/errors.ts +118 -0
  19. package/src/core/logger.ts +269 -0
  20. package/src/core/memory-usage.ts +84 -0
  21. package/src/core/metrics.ts +291 -0
  22. package/src/core/model-alias.ts +77 -0
  23. package/src/core/model-registry.ts +544 -0
  24. package/src/core/mutex.ts +119 -0
  25. package/src/core/paths.ts +199 -0
  26. package/src/core/prompt-limits.ts +214 -0
  27. package/src/core/reasoning-effort.ts +102 -0
  28. package/src/core/stream-registry.ts +96 -0
  29. package/src/core/waf-isolation.ts +117 -0
  30. package/src/core/watchdog.ts +195 -0
  31. package/src/delete-chats.ts +23 -0
  32. package/src/index.ts +64 -0
  33. package/src/login.ts +147 -0
  34. package/src/reset-cooldowns.ts +11 -0
  35. package/src/routes/anthropic/index.ts +355 -0
  36. package/src/routes/anthropic/translate.ts +522 -0
  37. package/src/routes/anthropic/types.ts +154 -0
  38. package/src/routes/anthropic/validation.ts +144 -0
  39. package/src/routes/chat/account.ts +1817 -0
  40. package/src/routes/chat/context.ts +241 -0
  41. package/src/routes/chat/errors.ts +85 -0
  42. package/src/routes/chat/helpers.ts +268 -0
  43. package/src/routes/chat/index.ts +618 -0
  44. package/src/routes/chat/media.ts +285 -0
  45. package/src/routes/chat/retry-policy.ts +754 -0
  46. package/src/routes/chat/stop.ts +98 -0
  47. package/src/routes/chat/streaming.ts +2710 -0
  48. package/src/routes/chat/validation.ts +526 -0
  49. package/src/routes/chat.ts +2 -0
  50. package/src/routes/completions.ts +290 -0
  51. package/src/routes/images.ts +139 -0
  52. package/src/routes/responses/adapter.ts +503 -0
  53. package/src/routes/responses/index.ts +405 -0
  54. package/src/routes/responses/state.ts +230 -0
  55. package/src/routes/responses/streaming.ts +528 -0
  56. package/src/routes/responses/types.ts +285 -0
  57. package/src/routes/responses/validation.ts +202 -0
  58. package/src/routes/upload.ts +731 -0
  59. package/src/routes/videos.ts +214 -0
  60. package/src/services/auth-playwright.ts +173 -0
  61. package/src/services/captcha-coordinator.ts +161 -0
  62. package/src/services/captcha-solver.ts +553 -0
  63. package/src/services/chat-cleanup.ts +80 -0
  64. package/src/services/context-meter.ts +317 -0
  65. package/src/services/fingerprint.ts +242 -0
  66. package/src/services/human-behavior.ts +173 -0
  67. package/src/services/media-generation.ts +1748 -0
  68. package/src/services/playwright.ts +2800 -0
  69. package/src/services/qwen-chat-pool.ts +345 -0
  70. package/src/services/qwen-errors.ts +133 -0
  71. package/src/services/qwen-headers.ts +79 -0
  72. package/src/services/qwen-thread-state.ts +393 -0
  73. package/src/services/qwen-url.ts +19 -0
  74. package/src/services/qwen.ts +3126 -0
  75. package/src/services/session-keeper.ts +88 -0
  76. package/src/services/token-estimation-metrics.ts +118 -0
  77. package/src/sync/claude-code.ts +75 -0
  78. package/src/sync/codex.ts +123 -0
  79. package/src/sync/index.ts +362 -0
  80. package/src/sync/omp.ts +105 -0
  81. package/src/sync/opencode.ts +214 -0
  82. package/src/sync/types.ts +53 -0
  83. package/src/sync/utils.ts +27 -0
  84. package/src/sync-clients.ts +189 -0
  85. package/src/tools/instructions.ts +137 -0
  86. package/src/tools/manifest.ts +81 -0
  87. package/src/tools/parser.ts +2989 -0
  88. package/src/tools/toolcall-tags.ts +142 -0
  89. package/src/tools/types.ts +53 -0
  90. package/src/tui/app.ts +264 -0
  91. package/src/tui/index.ts +61 -0
  92. package/src/tui/markdown.ts +258 -0
  93. package/src/tui/proxy-client.ts +326 -0
  94. package/src/tui/screen.ts +278 -0
  95. package/src/tui/server-manager.ts +270 -0
  96. package/src/tui/theme.ts +432 -0
  97. package/src/tui/types.ts +33 -0
  98. package/src/tui/views/accounts-view.ts +656 -0
  99. package/src/tui/views/chat-view.ts +823 -0
  100. package/src/tui/views/logs-view.ts +413 -0
  101. package/src/tui/views/status-view.ts +204 -0
  102. package/src/tui/views/storage-view.ts +291 -0
  103. package/src/tui/views/sync-view.ts +409 -0
  104. package/src/types/ali-oss.d.ts +32 -0
  105. package/src/utils/context-truncation.ts +84 -0
  106. package/src/utils/json.ts +380 -0
  107. package/src/utils/session-id.ts +37 -0
  108. package/src/utils/tool-call-guard.ts +85 -0
  109. package/src/utils/types.ts +109 -0
@@ -0,0 +1,214 @@
1
+ import type { Context } from "hono";
2
+ import {
3
+ generateVideo,
4
+ isSupportedMediaSize,
5
+ MEDIA_SIZE_OPTIONS,
6
+ pollVideoTask,
7
+ supportsPromptMediaGeneration,
8
+ } from "../services/media-generation.ts";
9
+ import { logger } from "../core/logger.ts";
10
+ import { sendOpenAIError } from "../api/error-helpers.ts";
11
+ import { NotFoundError, ValidationError } from "../core/errors.ts";
12
+
13
+ const DEFAULT_SIZE = "16:9";
14
+
15
+ const TASK_TTL_MS = 60 * 60_000;
16
+
17
+ type MediaTaskStatus = "pending" | "running" | "completed" | "failed";
18
+
19
+ interface VideoTaskEntry {
20
+ accountId: string;
21
+ chatId: string;
22
+ createdAt: number;
23
+ status: MediaTaskStatus;
24
+ videoUrl?: string;
25
+ }
26
+
27
+ interface VideosGenerationsRequest {
28
+ model?: unknown;
29
+ prompt?: unknown;
30
+ size?: unknown;
31
+ wait?: unknown;
32
+ }
33
+
34
+ const videoTasks = new Map<string, VideoTaskEntry>();
35
+
36
+ function cleanupExpiredTasks(): void {
37
+ const cutoff = Date.now() - TASK_TTL_MS;
38
+ for (const [taskId, entry] of videoTasks) {
39
+ if (entry.createdAt < cutoff) {
40
+ videoTasks.delete(taskId);
41
+ }
42
+ }
43
+ }
44
+
45
+ function validationError(message: string, param: string): ValidationError {
46
+ const err = new ValidationError(message);
47
+ err.param = param;
48
+ return err;
49
+ }
50
+
51
+ export async function videosGenerations(c: Context): Promise<Response> {
52
+ cleanupExpiredTasks();
53
+
54
+ let body: VideosGenerationsRequest;
55
+ try {
56
+ body = await c.req.json();
57
+ } catch {
58
+ return sendOpenAIError(c, new ValidationError("Request body must be valid JSON"));
59
+ }
60
+
61
+ const prompt = typeof body.prompt === "string" ? body.prompt.trim() : "";
62
+ if (!prompt) {
63
+ return sendOpenAIError(
64
+ c,
65
+ validationError("`prompt` must be a non-empty string", "prompt"),
66
+ );
67
+ }
68
+
69
+ const size = body.size === undefined ? DEFAULT_SIZE : body.size;
70
+ if (!isSupportedMediaSize(size)) {
71
+ return sendOpenAIError(
72
+ c,
73
+ validationError(
74
+ `\`size\` must be one of: ${MEDIA_SIZE_OPTIONS.join(", ")}`,
75
+ "size",
76
+ ),
77
+ );
78
+ }
79
+
80
+ const model =
81
+ typeof body.model === "string" && body.model.trim()
82
+ ? body.model.trim()
83
+ : "";
84
+ if (!model) {
85
+ return sendOpenAIError(
86
+ c,
87
+ validationError("`model` must be the model selected by the client", "model"),
88
+ );
89
+ }
90
+ if (!supportsPromptMediaGeneration(model, "video")) {
91
+ return sendOpenAIError(
92
+ c,
93
+ validationError(
94
+ `Model \`${model}\` requires a reference image and is not available through prompt-only video generation yet`,
95
+ "model",
96
+ ),
97
+ );
98
+ }
99
+ const wait = body.wait !== false;
100
+
101
+ logger.info("Video generation request", {
102
+ model,
103
+ size,
104
+ wait,
105
+ });
106
+
107
+ try {
108
+ const result = await generateVideo({
109
+ model,
110
+ prompt,
111
+ size,
112
+ waitForCompletion: wait,
113
+ });
114
+
115
+ const created = Math.floor(Date.now() / 1000);
116
+
117
+ // The upstream can return the video URL inline, without a task id.
118
+ if (!result.task_id) {
119
+ if (result.status === "completed" && result.video_url) {
120
+ return c.json({
121
+ created,
122
+ task_id: "",
123
+ status: "completed",
124
+ data: [{ url: result.video_url }],
125
+ });
126
+ }
127
+ return sendOpenAIError(
128
+ c,
129
+ new Error("Video generation returned no task or video URL"),
130
+ 500,
131
+ );
132
+ }
133
+
134
+ videoTasks.set(result.task_id, {
135
+ accountId: result.accountId,
136
+ chatId: result.chatId,
137
+ createdAt: Date.now(),
138
+ status: result.status,
139
+ videoUrl: result.video_url,
140
+ });
141
+
142
+ if (result.status === "failed") {
143
+ logger.error("Video generation task failed", { taskId: result.task_id });
144
+ return sendOpenAIError(c, new Error("Video generation failed"), 500);
145
+ }
146
+
147
+ if (result.status === "completed") {
148
+ return c.json({
149
+ created,
150
+ task_id: result.task_id,
151
+ status: "completed",
152
+ data: [{ url: result.video_url }],
153
+ });
154
+ }
155
+
156
+ // wait=false, or the upstream poll window elapsed before completion.
157
+ return c.json({
158
+ created,
159
+ task_id: result.task_id,
160
+ status: result.status,
161
+ });
162
+ } catch (error) {
163
+ logger.error("Video generation failed", {
164
+ model,
165
+ error: error instanceof Error ? error.message : String(error),
166
+ });
167
+ return sendOpenAIError(c, error, 500);
168
+ }
169
+ }
170
+
171
+ export async function videoTaskStatus(c: Context): Promise<Response> {
172
+ cleanupExpiredTasks();
173
+
174
+ const taskId = c.req.param("taskId");
175
+ if (!taskId) {
176
+ return sendOpenAIError(c, new NotFoundError("Video task not found"));
177
+ }
178
+
179
+ const entry = videoTasks.get(taskId);
180
+ if (!entry) {
181
+ return sendOpenAIError(c, new NotFoundError(`Video task not found: ${taskId}`));
182
+ }
183
+
184
+ const wait = c.req.query("wait") === "true";
185
+
186
+ try {
187
+ const isTerminal = entry.status === "completed" || entry.status === "failed";
188
+ if (wait && !isTerminal) {
189
+ // pollVideoTask blocks until a terminal status or its internal timeout.
190
+ const result = await pollVideoTask({ taskId, accountId: entry.accountId });
191
+ entry.status = result.status;
192
+ entry.videoUrl = result.video_url ?? entry.videoUrl;
193
+ if (result.status === "failed") {
194
+ logger.error("Video task failed", {
195
+ taskId,
196
+ error: result.error ?? "unknown",
197
+ });
198
+ }
199
+ }
200
+
201
+ return c.json({
202
+ task_id: taskId,
203
+ status: entry.status,
204
+ video_url: entry.videoUrl ?? null,
205
+ created: Math.floor(entry.createdAt / 1000),
206
+ });
207
+ } catch (error) {
208
+ logger.error("Video task status check failed", {
209
+ taskId,
210
+ error: error instanceof Error ? error.message : String(error),
211
+ });
212
+ return sendOpenAIError(c, error, 500);
213
+ }
214
+ }
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }