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,385 @@
1
+ import { promisify } from "util";
2
+ import { brotliCompress, brotliDecompress, constants } from "zlib";
3
+ import { config } from "../core/config.js";
4
+ import { metrics } from "../core/metrics.js";
5
+
6
+ const compressAsync = promisify(brotliCompress);
7
+ const decompressAsync = promisify(brotliDecompress);
8
+
9
+ export type CacheKey =
10
+ | `auth:${string}`
11
+ | `session:${string}`
12
+ | `prompt:${string}`
13
+ | `response:${string}`
14
+ | `rate:${string}`
15
+ | `topic:${string}`;
16
+
17
+ interface CacheEntry<T> {
18
+ value: T;
19
+ expiresAt: number;
20
+ compressed?: boolean;
21
+ }
22
+
23
+ export class MemoryCache {
24
+ private connected = false;
25
+ private store: Map<string, CacheEntry<any>>;
26
+ private defaultTTL: number;
27
+ private prefix: string;
28
+ private cleanupInterval: NodeJS.Timeout | null;
29
+ private hits: number = 0;
30
+ private misses: number = 0;
31
+ private totalBytesSaved: number = 0;
32
+ private totalCompressedBytes: number = 0;
33
+ private compressionCount: number = 0;
34
+ private mutationQueue: Promise<void> = Promise.resolve();
35
+ // Cache for compiled regex patterns in scan operations (upstream: a63f054)
36
+ private scanRegexCache: Map<string, RegExp> = new Map();
37
+
38
+ constructor(options?: { prefix?: string; defaultTTL?: number }) {
39
+ this.prefix = options?.prefix || "qwenproxy:";
40
+ this.defaultTTL = options?.defaultTTL || config.cache.defaultTTL;
41
+ this.store = new Map();
42
+ this.cleanupInterval = null;
43
+
44
+ this.startCleanup();
45
+ }
46
+
47
+ private startCleanup(): void {
48
+ this.cleanupInterval = setInterval(() => {
49
+ if (this.store.size === 0) return;
50
+ const now = Date.now();
51
+ for (const [key, entry] of this.store.entries()) {
52
+ if (entry.expiresAt <= now) {
53
+ this.store.delete(key);
54
+ }
55
+ }
56
+ }, 60000);
57
+ this.cleanupInterval.unref?.();
58
+ }
59
+
60
+ async connect(): Promise<void> {
61
+ this.connected = true;
62
+ }
63
+
64
+ async set<T>(key: CacheKey, value: T, ttl?: number): Promise<void> {
65
+ const serialized = this.serialize(value);
66
+ let storedValue: string | Buffer = serialized;
67
+ let compressed = false;
68
+ let originalSize: number;
69
+
70
+ if (config.cache.compression.enabled) {
71
+ // Encode once and reuse for both the size check and compression,
72
+ // avoiding a second UTF-8 pass over large values.
73
+ const encoded = Buffer.from(serialized);
74
+ originalSize = encoded.length;
75
+ if (originalSize >= config.cache.compression.threshold) {
76
+ try {
77
+ const compressedBuffer = await compressAsync(encoded, {
78
+ params: {
79
+ [constants.BROTLI_PARAM_QUALITY]: config.cache.compression.level,
80
+ },
81
+ });
82
+
83
+ const compressedSize = compressedBuffer.length;
84
+ const saved = originalSize - compressedSize;
85
+
86
+ if (saved > 0) {
87
+ storedValue = compressedBuffer;
88
+ compressed = true;
89
+ this.totalBytesSaved += saved;
90
+ this.totalCompressedBytes += compressedSize;
91
+ this.compressionCount++;
92
+
93
+ metrics.increment("cache.compression.bytes.saved", saved);
94
+ metrics.histogram(
95
+ "cache.compression.ratio",
96
+ originalSize / compressedSize,
97
+ );
98
+ }
99
+ } catch (err) {
100
+ // Compression failed, store uncompressed
101
+ }
102
+ }
103
+ } else {
104
+ originalSize = Buffer.byteLength(serialized);
105
+ }
106
+
107
+ const effectiveTTL = ttl || this.defaultTTL;
108
+ const fullKey = this.prefix + key;
109
+
110
+ this.store.set(fullKey, {
111
+ value: storedValue,
112
+ expiresAt: Date.now() + effectiveTTL * 1000,
113
+ compressed,
114
+ });
115
+
116
+ metrics.increment("cache.set");
117
+ metrics.histogram("cache.value.size", originalSize);
118
+ }
119
+
120
+ async get<T>(key: CacheKey): Promise<T | null> {
121
+ const fullKey = this.prefix + key;
122
+ const entry = this.store.get(fullKey);
123
+
124
+ if (!entry || entry.expiresAt <= Date.now()) {
125
+ if (entry) this.store.delete(fullKey);
126
+ this.misses++;
127
+ metrics.increment("cache.miss");
128
+ return null;
129
+ }
130
+
131
+ this.hits++;
132
+ metrics.increment("cache.hit");
133
+
134
+ // Decompress if needed
135
+ if (entry.compressed && Buffer.isBuffer(entry.value)) {
136
+ try {
137
+ const decompressed = await decompressAsync(entry.value);
138
+ return this.deserialize<T>(decompressed.toString());
139
+ } catch (err) {
140
+ // Decompression failed, return null
141
+ this.store.delete(fullKey);
142
+ return null;
143
+ }
144
+ }
145
+
146
+ if (entry.compressed) {
147
+ this.store.delete(fullKey);
148
+ return null;
149
+ }
150
+
151
+ const serialized =
152
+ typeof entry.value === "string" ? entry.value : String(entry.value);
153
+
154
+ return this.deserialize<T>(serialized);
155
+ }
156
+
157
+ async delete(key: CacheKey): Promise<void> {
158
+ const fullKey = this.prefix + key;
159
+ this.store.delete(fullKey);
160
+ metrics.increment("cache.deleted");
161
+ }
162
+
163
+ async exists(key: CacheKey): Promise<boolean> {
164
+ const fullKey = this.prefix + key;
165
+ const entry = this.store.get(fullKey);
166
+ if (!entry || entry.expiresAt <= Date.now()) {
167
+ if (entry) this.store.delete(fullKey);
168
+ return false;
169
+ }
170
+ return true;
171
+ }
172
+
173
+ async setWithNX<T>(key: CacheKey, value: T, ttl?: number): Promise<boolean> {
174
+ return this.withMutation(async () => {
175
+ const fullKey = this.prefix + key;
176
+ const entry = this.store.get(fullKey);
177
+ if (entry && entry.expiresAt > Date.now()) {
178
+ return false;
179
+ }
180
+ if (entry) this.store.delete(fullKey);
181
+ await this.set(key, value, ttl);
182
+ return true;
183
+ });
184
+ }
185
+
186
+ async increment(
187
+ key: CacheKey,
188
+ by: number = 1,
189
+ ttl?: number,
190
+ ): Promise<number> {
191
+ return this.withMutation(async () => {
192
+ const currentValue = await this.get<number>(key);
193
+ const current =
194
+ typeof currentValue === "number" && Number.isFinite(currentValue)
195
+ ? currentValue
196
+ : 0;
197
+
198
+ const newValue = current + by;
199
+ const effectiveTTL = ttl || this.defaultTTL;
200
+ const fullKey = this.prefix + key;
201
+
202
+ this.store.set(fullKey, {
203
+ value: this.serialize(newValue),
204
+ expiresAt: Date.now() + effectiveTTL * 1000,
205
+ });
206
+
207
+ return newValue;
208
+ });
209
+ }
210
+
211
+ async getMulti<T>(keys: CacheKey[]): Promise<(T | null)[]> {
212
+ return Promise.all(keys.map((key) => this.get<T>(key)));
213
+ }
214
+
215
+ async scan(pattern: string, _count: number = 100): Promise<string[]> {
216
+ // Use cached regex for repeated patterns (upstream: a63f054)
217
+ let regex = this.scanRegexCache.get(pattern);
218
+ if (!regex) {
219
+ regex = new RegExp(this.prefix + pattern.replace(/\*/g, ".*"));
220
+ this.scanRegexCache.set(pattern, regex);
221
+ }
222
+ const now = Date.now();
223
+ const keys: string[] = [];
224
+
225
+ for (const [key, entry] of this.store.entries()) {
226
+ if (regex.test(key) && entry.expiresAt > now) {
227
+ keys.push(key);
228
+ }
229
+ }
230
+ return keys;
231
+ }
232
+
233
+ async flush(pattern?: string): Promise<void> {
234
+ if (pattern) {
235
+ const keys = await this.scan(pattern);
236
+ for (const key of keys) {
237
+ this.store.delete(key);
238
+ }
239
+ } else {
240
+ this.store.clear();
241
+ }
242
+ metrics.increment("cache.flushed");
243
+ }
244
+
245
+ async getStats(): Promise<{
246
+ connected: boolean;
247
+ keysCount: number;
248
+ memoryUsage: string;
249
+ hitRatio: number;
250
+ compressionRatio: number;
251
+ bytesSaved: number;
252
+ }> {
253
+ const now = Date.now();
254
+ let validKeys = 0;
255
+ let totalBytes = 0;
256
+ for (const [key, entry] of this.store.entries()) {
257
+ if (entry.expiresAt > now) {
258
+ validKeys++;
259
+ const valueSize = Buffer.isBuffer(entry.value)
260
+ ? entry.value.length
261
+ : Buffer.byteLength(String(entry.value));
262
+ totalBytes += valueSize + Buffer.byteLength(key);
263
+ }
264
+ }
265
+
266
+ const totalRequests = this.hits + this.misses;
267
+ const hitRatio = totalRequests > 0 ? this.hits / totalRequests : 0;
268
+ const avgCompressionRatio =
269
+ this.totalCompressedBytes > 0
270
+ ? (this.totalCompressedBytes + this.totalBytesSaved) /
271
+ this.totalCompressedBytes
272
+ : 1;
273
+
274
+ // Update gauge metrics
275
+ metrics.gauge("cache.hit.ratio", hitRatio);
276
+ metrics.gauge("cache.memory.usage.bytes", totalBytes);
277
+ metrics.gauge("cache.entries.count", validKeys);
278
+
279
+ return {
280
+ connected: this.connected,
281
+ keysCount: validKeys,
282
+ memoryUsage: `${(totalBytes / 1024).toFixed(2)}KB`,
283
+ hitRatio,
284
+ compressionRatio: avgCompressionRatio,
285
+ bytesSaved: this.totalBytesSaved,
286
+ };
287
+ }
288
+
289
+ private async withMutation<T>(fn: () => Promise<T>): Promise<T> {
290
+ const previous = this.mutationQueue;
291
+ let release!: () => void;
292
+ this.mutationQueue = new Promise<void>((resolve) => {
293
+ release = resolve;
294
+ });
295
+
296
+ await previous;
297
+ try {
298
+ return await fn();
299
+ } finally {
300
+ release();
301
+ }
302
+ }
303
+
304
+ async close(): Promise<void> {
305
+ if (this.cleanupInterval) {
306
+ clearInterval(this.cleanupInterval);
307
+ this.cleanupInterval = null;
308
+ }
309
+ this.store.clear();
310
+ this.connected = false;
311
+ }
312
+
313
+ // Preserve primitive types without coercing numeric-looking strings.
314
+ private serialize<T>(value: T): string {
315
+ if (value === null) return "l:";
316
+ if (value === undefined) return "u:";
317
+
318
+ switch (typeof value) {
319
+ case "string":
320
+ return `s:${value}`;
321
+ case "number":
322
+ return `n:${value}`;
323
+ case "boolean":
324
+ return value ? "b:1" : "b:0";
325
+ default:
326
+ return `j:${JSON.stringify(value)}`;
327
+ }
328
+ }
329
+
330
+ private deserialize<T>(serialized: string): T {
331
+ if (serialized.length >= 2 && serialized[1] === ":") {
332
+ const type = serialized[0];
333
+ const payload = serialized.slice(2);
334
+
335
+ switch (type) {
336
+ case "l":
337
+ return null as T;
338
+ case "u":
339
+ return undefined as T;
340
+ case "s":
341
+ return payload as T;
342
+ case "n":
343
+ return Number(payload) as T;
344
+ case "b":
345
+ return (payload === "1") as T;
346
+ case "j":
347
+ return JSON.parse(payload) as T;
348
+ }
349
+ }
350
+
351
+ if (serialized === "null") return null as T;
352
+ if (serialized === "undefined") return undefined as T;
353
+ if (serialized === "true") return true as T;
354
+ if (serialized === "false") return false as T;
355
+ if (/^-?\d+(\.\d+)?$/.test(serialized)) {
356
+ return Number(serialized) as T;
357
+ }
358
+
359
+ try {
360
+ return JSON.parse(serialized) as T;
361
+ } catch {
362
+ return serialized as T;
363
+ }
364
+ }
365
+
366
+ // Invalidate entries by pattern (topic-based)
367
+ async invalidateByPattern(pattern: string): Promise<number> {
368
+ const keys = await this.scan(pattern);
369
+ let count = 0;
370
+ for (const key of keys) {
371
+ this.store.delete(key);
372
+ count++;
373
+ }
374
+ if (count > 0) {
375
+ metrics.increment("cache.topic.invalidation", count);
376
+ }
377
+ return count;
378
+ }
379
+
380
+ // Invalidate all entries for a session
381
+ async invalidateBySession(sessionId: string): Promise<number> {
382
+ const pattern = `*session:*${sessionId}*`;
383
+ return this.invalidateByPattern(pattern);
384
+ }
385
+ }
@@ -0,0 +1,204 @@
1
+ import "dotenv/config";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import { chromium } from "patchright";
6
+ import { pruneAllPlaywrightProfiles } from "./services/playwright.ts";
7
+
8
+ export function formatBytes(bytes: number): string {
9
+ if (bytes < 1024) return `${bytes} B`;
10
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
11
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
12
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
13
+ }
14
+
15
+ export function getDirStats(dir: string): { bytes: number; files: number } {
16
+ let bytes = 0;
17
+ let files = 0;
18
+ function walk(d: string) {
19
+ try {
20
+ const entries = fs.readdirSync(d, { withFileTypes: true });
21
+ for (const e of entries) {
22
+ const full = path.join(d, e.name);
23
+ if (e.isDirectory()) {
24
+ walk(full);
25
+ } else if (e.isFile()) {
26
+ try {
27
+ bytes += fs.statSync(full).size;
28
+ files++;
29
+ } catch {}
30
+ }
31
+ }
32
+ } catch {}
33
+ }
34
+ walk(dir);
35
+ return { bytes, files };
36
+ }
37
+
38
+ export async function cleanPlaywrightBrowsers(cleanUnused: boolean): Promise<{
39
+ activeBrowserDir: string | null;
40
+ unusedDirs: { name: string; path: string; size: string; bytes: number }[];
41
+ freedBytes: number;
42
+ }> {
43
+ let activeBrowserDir: string | null = null;
44
+ let activeRevision: string | null = null;
45
+ let msPlaywrightDir: string | null = null;
46
+
47
+ try {
48
+ const execPath = chromium.executablePath();
49
+ // E.g. C:\Users\...\AppData\Local\ms-playwright\chromium-1234\chrome-win64\chrome.exe
50
+ // The browser folder is the first directory under ms-playwright
51
+ const resolvedPlaywrightDir = path.resolve(execPath, "..", "..", "..");
52
+ const rel = path.relative(resolvedPlaywrightDir, execPath);
53
+ const topFolder = rel.split(path.sep)[0];
54
+ activeBrowserDir = topFolder;
55
+ msPlaywrightDir = resolvedPlaywrightDir;
56
+
57
+ const matchRev = topFolder.match(/-(\d+)$/);
58
+ if (matchRev) {
59
+ activeRevision = matchRev[1];
60
+ }
61
+ } catch {}
62
+
63
+ if (!msPlaywrightDir || !fs.existsSync(msPlaywrightDir)) {
64
+ const defaultPlaywrightDir =
65
+ process.env.PLAYWRIGHT_BROWSERS_PATH ||
66
+ (process.platform === "win32"
67
+ ? path.join(os.homedir(), "AppData", "Local", "ms-playwright")
68
+ : process.platform === "darwin"
69
+ ? path.join(os.homedir(), "Library", "Caches", "ms-playwright")
70
+ : path.join(os.homedir(), ".cache", "ms-playwright"));
71
+ if (fs.existsSync(defaultPlaywrightDir)) {
72
+ msPlaywrightDir = defaultPlaywrightDir;
73
+ }
74
+ }
75
+
76
+ const unusedDirs: { name: string; path: string; size: string; bytes: number }[] = [];
77
+ let freedBytes = 0;
78
+
79
+ if (msPlaywrightDir && fs.existsSync(msPlaywrightDir)) {
80
+ try {
81
+ const entries = fs.readdirSync(msPlaywrightDir, { withFileTypes: true });
82
+ for (const entry of entries) {
83
+ if (!entry.isDirectory()) continue;
84
+ const folderName = entry.name;
85
+
86
+ // Never delete:
87
+ // 1. Exact active browser folder (e.g. chromium-1234)
88
+ if (folderName === activeBrowserDir) continue;
89
+
90
+ // 2. Headless shell sharing the active revision (e.g. chromium_headless_shell-1234)
91
+ if (activeRevision && folderName.includes(activeRevision)) continue;
92
+
93
+ // 3. System tools and critical link directories
94
+ if (
95
+ folderName.startsWith("winldd") ||
96
+ folderName.startsWith("ffmpeg") ||
97
+ folderName.startsWith(".links") ||
98
+ folderName.startsWith(".registry")
99
+ ) {
100
+ continue;
101
+ }
102
+
103
+ const fullPath = path.join(msPlaywrightDir, folderName);
104
+ const { bytes } = getDirStats(fullPath);
105
+ if (bytes > 0) {
106
+ unusedDirs.push({
107
+ name: folderName,
108
+ path: fullPath,
109
+ size: formatBytes(bytes),
110
+ bytes,
111
+ });
112
+ }
113
+ }
114
+
115
+ if (cleanUnused && unusedDirs.length > 0) {
116
+ for (const item of unusedDirs) {
117
+ try {
118
+ fs.rmSync(item.path, { recursive: true, force: true });
119
+ freedBytes += item.bytes;
120
+ } catch (err) {
121
+ console.warn(`[CleanCache] Warning: could not remove ${item.name}:`, err);
122
+ }
123
+ }
124
+ }
125
+ } catch (err) {
126
+ console.warn("[CleanCache] Error reading ms-playwright directory:", err);
127
+ }
128
+ }
129
+
130
+ return { activeBrowserDir, unusedDirs, freedBytes };
131
+ }
132
+
133
+ async function main() {
134
+ const args = process.argv.slice(2);
135
+ const cleanAll = args.includes("--all") || args.includes("--browsers");
136
+
137
+ console.log("==================================================");
138
+ console.log(" [QwenProxy] Cache & Storage Optimization Tool");
139
+ console.log("==================================================\n");
140
+
141
+ // 1. Profile Transient Cache Pruning (V8 Code Cache, GPU Cache)
142
+ console.log("1. Limpando caches transitórios dos perfis (data/qwen_profiles/)...");
143
+ const profileResult = pruneAllPlaywrightProfiles();
144
+ if (profileResult.totalFreedFiles > 0) {
145
+ console.log(
146
+ ` [OK] Perfis limpos com sucesso!`,
147
+ );
148
+ console.log(
149
+ ` Espaço liberado: ${formatBytes(profileResult.totalFreedBytes)} em ${profileResult.totalFreedFiles} arquivos (${profileResult.profilesCleaned} perfil(is)).`,
150
+ );
151
+ console.log(
152
+ ` (Todos os cookies, sessões e logins foram 100% preservados!)`,
153
+ );
154
+ } else {
155
+ console.log(" [OK] Nenhum cache transitório acumulado nos perfis.");
156
+ }
157
+ console.log("");
158
+
159
+ // 2. Playwright Browser Binaries Cleanup
160
+ console.log("2. Inspecionando diretório global do Playwright (ms-playwright)...");
161
+ const browserResult = await cleanPlaywrightBrowsers(cleanAll);
162
+
163
+ if (browserResult.activeBrowserDir) {
164
+ console.log(` Navegador ativo em uso pelo QwenProxy: ${browserResult.activeBrowserDir}`);
165
+ }
166
+
167
+ if (browserResult.unusedDirs.length > 0) {
168
+ const totalReclaimable = browserResult.unusedDirs.reduce((acc, d) => acc + d.bytes, 0);
169
+
170
+ if (cleanAll) {
171
+ console.log(` [OK] ${browserResult.unusedDirs.length} navegador(es) não utilizado(s) removido(s):`);
172
+ for (const d of browserResult.unusedDirs) {
173
+ console.log(` - ${d.name} (${d.size})`);
174
+ }
175
+ console.log(` Total recuperado no SSD: ${formatBytes(browserResult.freedBytes)}!`);
176
+ } else {
177
+ console.log(` [INFO] Encontrados ${browserResult.unusedDirs.length} navegador(es) legados/não utilizados no seu SSD:`);
178
+ for (const d of browserResult.unusedDirs) {
179
+ console.log(` - ${d.name} (${d.size})`);
180
+ }
181
+ console.log(` Espaço recuperável no SSD: ${formatBytes(totalReclaimable)}.`);
182
+ console.log(` Para liberar esse espaço automaticamente, execute:`);
183
+ console.log(` npm run clean:all\n`);
184
+ }
185
+ } else {
186
+ console.log(" [OK] O diretório do Playwright já está enxuto (sem navegadores órfãos).\n");
187
+ }
188
+
189
+ console.log("==================================================");
190
+ console.log(" Otimização concluída com segurança!");
191
+ console.log("==================================================\n");
192
+ }
193
+
194
+ const isDirectRun =
195
+ process.argv[1] &&
196
+ (process.argv[1].endsWith("clean-cache.ts") ||
197
+ process.argv[1].endsWith("clean-cache.js"));
198
+
199
+ if (isDirectRun) {
200
+ main().catch((err) => {
201
+ console.error("[CleanCache] Erro fatal durante a limpeza:", err);
202
+ process.exit(1);
203
+ });
204
+ }