qwenproxy-cli 1.0.0 → 1.0.2

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 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +77 -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 +2878 -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 +259 -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/update-cli.ts +121 -0
  105. package/src/utils/context-truncation.ts +84 -84
  106. package/src/utils/json.ts +380 -380
  107. package/src/utils/session-id.ts +37 -37
  108. package/src/utils/tool-call-guard.ts +84 -84
  109. package/src/utils/types.ts +109 -109
@@ -1,204 +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
- }
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
+ }