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,84 @@
1
+ import v8 from "v8";
2
+ import os from "os";
3
+
4
+ /**
5
+ * Heap pressure relative to V8 heap_size_limit (not heapTotal).
6
+ * heapUsed/heapTotal is almost always high (~95%+) and caused false criticals.
7
+ */
8
+ export interface HeapUsageSnapshot {
9
+ heapUsed: number;
10
+ heapTotal: number;
11
+ heapSizeLimit: number;
12
+ rss: number;
13
+ usagePercent: number;
14
+ }
15
+
16
+ export function getHeapUsageSnapshot(
17
+ mem: NodeJS.MemoryUsage = process.memoryUsage(),
18
+ heapSizeLimit: number = v8.getHeapStatistics().heap_size_limit,
19
+ ): HeapUsageSnapshot {
20
+ const limit =
21
+ Number.isFinite(heapSizeLimit) && heapSizeLimit > 0
22
+ ? heapSizeLimit
23
+ : Math.max(mem.heapTotal, 1);
24
+ const usagePercent = (mem.heapUsed / limit) * 100;
25
+ return {
26
+ heapUsed: mem.heapUsed,
27
+ heapTotal: mem.heapTotal,
28
+ heapSizeLimit: limit,
29
+ rss: mem.rss,
30
+ usagePercent,
31
+ };
32
+ }
33
+
34
+ export function classifyRamUsage(
35
+ usagePercent: number,
36
+ warningThreshold: number,
37
+ criticalThreshold: number,
38
+ ): "ok" | "warning" | "critical" {
39
+ if (usagePercent > criticalThreshold) return "critical";
40
+ if (usagePercent > warningThreshold) return "warning";
41
+ return "ok";
42
+ }
43
+
44
+ /**
45
+ * RSS pressure relative to TOTAL system memory. The heap-vs-limit ratio misses
46
+ * Playwright browser processes (RSS lives outside the V8 heap); RSS vs total
47
+ * RAM is the metric that actually predicts OOM on a VPS.
48
+ */
49
+ export interface RssUsageSnapshot {
50
+ rss: number;
51
+ totalSystemMemory: number;
52
+ /** RSS as a percentage of total system memory. */
53
+ usagePercent: number;
54
+ }
55
+
56
+ export function getRssUsageSnapshot(
57
+ mem: NodeJS.MemoryUsage = process.memoryUsage(),
58
+ totalSystemMemory: number = os.totalmem(),
59
+ ): RssUsageSnapshot {
60
+ const usagePercent =
61
+ Number.isFinite(totalSystemMemory) && totalSystemMemory > 0
62
+ ? (mem.rss / totalSystemMemory) * 100
63
+ : 0;
64
+ return {
65
+ rss: mem.rss,
66
+ totalSystemMemory,
67
+ usagePercent,
68
+ };
69
+ }
70
+
71
+ /** % of system RAM used by this process (RSS), rounded to one decimal. */
72
+ export function getMemoryUsagePct(
73
+ mem: NodeJS.MemoryUsage = process.memoryUsage(),
74
+ totalSystemMemory: number = os.totalmem(),
75
+ ): number {
76
+ const snap = getRssUsageSnapshot(mem, totalSystemMemory);
77
+ if (
78
+ !Number.isFinite(snap.rss) ||
79
+ snap.totalSystemMemory <= 0
80
+ ) {
81
+ return 0;
82
+ }
83
+ return Number(snap.usagePercent.toFixed(1));
84
+ }
@@ -0,0 +1,291 @@
1
+ import { EventEmitter } from "events";
2
+ import { config } from "./config.js";
3
+ import { getHeapUsageSnapshot, getRssUsageSnapshot } from "./memory-usage.js";
4
+
5
+ interface MetricPoint {
6
+ value: number;
7
+ timestamp: number;
8
+ labels?: Record<string, string>;
9
+ }
10
+
11
+ type MetricType = "counter" | "gauge" | "histogram" | "summary";
12
+
13
+ interface MetricDefinition {
14
+ name: string;
15
+ type: MetricType;
16
+ help: string;
17
+ values: Map<string, MetricPoint>;
18
+ histogramBuckets?: number[];
19
+ }
20
+
21
+ export class Metrics extends EventEmitter {
22
+ private metrics: Map<string, MetricDefinition> = new Map();
23
+ private collectionInterval: NodeJS.Timeout | null = null;
24
+
25
+ constructor() {
26
+ super();
27
+ this.registerDefaults();
28
+ }
29
+
30
+ private registerDefaults(): void {
31
+ const defaults: Array<[string, MetricType, string]> = [
32
+ // Core request metrics
33
+ ["requests.total", "counter", "Total requests processed"],
34
+ ["requests.errors", "counter", "Total request errors"],
35
+ ["latency.request", "histogram", "Request latency (ms)"],
36
+
37
+ // Stream metrics
38
+ ["streams.active", "gauge", "Active SSE streams"],
39
+ ["streams.errors", "counter", "Stream errors"],
40
+
41
+ // CAPTCHA / anti-bot metrics
42
+ ["captcha.challenges.detected", "counter", "Detected CAPTCHA challenges"],
43
+ ["captcha.solves.succeeded", "counter", "Successful CAPTCHA solves"],
44
+ ["captcha.solves.failed", "counter", "Failed CAPTCHA solves"],
45
+ ["captcha.solve.duration", "histogram", "CAPTCHA solve duration (ms)"],
46
+
47
+ // Memory metrics
48
+ ["memory.heap.used", "gauge", "Heap memory used (bytes)"],
49
+ ["memory.heap.total", "gauge", "Heap memory total (bytes)"],
50
+ [
51
+ "memory.heap.limit",
52
+ "gauge",
53
+ "V8 heap_size_limit used for RAM pressure (bytes)",
54
+ ],
55
+ [
56
+ "memory.heap.usage_percent",
57
+ "gauge",
58
+ "Heap used percent vs heap_size_limit",
59
+ ],
60
+ ["memory.rss", "gauge", "Resident set size (bytes)"],
61
+ [
62
+ "memory.rss.usage_percent",
63
+ "gauge",
64
+ "RSS as percent of total system memory (RAM pressure signal)",
65
+ ],
66
+
67
+ // Cache metrics
68
+ ["cache.set", "counter", "Cache set operations"],
69
+ ["cache.hit", "counter", "Cache hits"],
70
+ ["cache.miss", "counter", "Cache misses"],
71
+ ["cache.deleted", "counter", "Cache deletions"],
72
+ ["cache.flushed", "counter", "Cache flushes"],
73
+ ["cache.value.size", "histogram", "Cache value size (bytes)"],
74
+ ["cache.get.latency", "histogram", "Cache get latency (ms)"],
75
+ ["cache.hit.ratio", "gauge", "Cache hit ratio (hits / (hits + misses))"],
76
+ [
77
+ "cache.compression.ratio",
78
+ "histogram",
79
+ "Compression ratio (original / compressed)",
80
+ ],
81
+ [
82
+ "cache.compression.bytes.saved",
83
+ "counter",
84
+ "Total bytes saved by compression",
85
+ ],
86
+ [
87
+ "cache.topic.invalidation",
88
+ "counter",
89
+ "Cache entries invalidated by topic change",
90
+ ],
91
+ [
92
+ "cache.memory.usage.bytes",
93
+ "gauge",
94
+ "Estimated cache memory usage (bytes)",
95
+ ],
96
+ ["cache.entries.count", "gauge", "Current number of cache entries"],
97
+ [
98
+ "topic.change.detected",
99
+ "counter",
100
+ "Detected conversation topic changes",
101
+ ],
102
+
103
+ // Watchdog metrics
104
+ [
105
+ "watchdog.ram.status",
106
+ "gauge",
107
+ "Watchdog RAM status (0=ok, 1=warning, 2=critical)",
108
+ ],
109
+ [
110
+ "watchdog.overall",
111
+ "gauge",
112
+ "Watchdog overall status (0=healthy, 1=degraded, 2=unhealthy)",
113
+ ],
114
+ ["watchdog.recovery.triggered", "counter", "Recovery attempts triggered"],
115
+ ["watchdog.recovery.success", "counter", "Successful recoveries"],
116
+ ["watchdog.recovery.failed", "counter", "Failed recoveries"],
117
+ ];
118
+
119
+ for (const [name, type, help] of defaults) {
120
+ this.metrics.set(name, {
121
+ name,
122
+ type,
123
+ help,
124
+ values: new Map(),
125
+ histogramBuckets:
126
+ type === "histogram"
127
+ ? [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000]
128
+ : undefined,
129
+ });
130
+ }
131
+ }
132
+
133
+ increment(
134
+ name: string,
135
+ value: number = 1,
136
+ labels?: Record<string, string>,
137
+ ): void {
138
+ const metric = this.metrics.get(name);
139
+ if (!metric || metric.type !== "counter") return;
140
+
141
+ const key = labels ? JSON.stringify(labels) : "default";
142
+ // Mutate in place to avoid reallocating a MetricPoint on every increment.
143
+ const point = metric.values.get(key);
144
+ if (point) {
145
+ point.value += value;
146
+ point.timestamp = Date.now();
147
+ } else {
148
+ metric.values.set(key, { value, timestamp: Date.now(), labels });
149
+ }
150
+ }
151
+
152
+ gauge(name: string, value: number, labels?: Record<string, string>): void {
153
+ const metric = this.metrics.get(name);
154
+ if (!metric || metric.type !== "gauge") return;
155
+
156
+ const key = labels ? JSON.stringify(labels) : "default";
157
+ const point = metric.values.get(key);
158
+ if (point) {
159
+ point.value = value;
160
+ point.timestamp = Date.now();
161
+ } else {
162
+ metric.values.set(key, { value, timestamp: Date.now(), labels });
163
+ }
164
+ }
165
+
166
+ histogram(
167
+ name: string,
168
+ value: number,
169
+ labels?: Record<string, string>,
170
+ ): void {
171
+ const metric = this.metrics.get(name);
172
+ if (!metric || metric.type !== "histogram") return;
173
+
174
+ const key = labels ? JSON.stringify(labels) : "default";
175
+ const existing = metric.values.get(key);
176
+ // Reuse the stored aggregate object instead of re-wrapping it each call.
177
+ let data: { count: number; sum: number; buckets: Map<number, number> };
178
+ if (existing && typeof existing.value === "object" && existing.value !== null) {
179
+ data = existing.value as { count: number; sum: number; buckets: Map<number, number> };
180
+ } else {
181
+ data = { count: 0, sum: 0, buckets: new Map<number, number>() };
182
+ }
183
+
184
+ data.count++;
185
+ data.sum += value;
186
+ const buckets = metric.histogramBuckets;
187
+ if (buckets) {
188
+ for (let i = 0; i < buckets.length; i++) {
189
+ const bucket = buckets[i];
190
+ if (value <= bucket) {
191
+ data.buckets.set(bucket, (data.buckets.get(bucket) || 0) + 1);
192
+ } else if (!data.buckets.has(bucket)) {
193
+ // Keep every bucket present for stable output, but skip redundant writes.
194
+ data.buckets.set(bucket, 0);
195
+ }
196
+ }
197
+ }
198
+
199
+ if (existing) {
200
+ existing.value = data as any;
201
+ existing.timestamp = Date.now();
202
+ } else {
203
+ metric.values.set(key, { value: data as any, timestamp: Date.now(), labels });
204
+ }
205
+ }
206
+
207
+ startCollection(): void {
208
+ if (this.collectionInterval) return;
209
+
210
+ this.collectionInterval = setInterval(() => {
211
+ this.collectSystemMetrics();
212
+ }, config.metrics.interval);
213
+ }
214
+
215
+ private collectSystemMetrics(): void {
216
+ const heap = getHeapUsageSnapshot();
217
+ const rss = getRssUsageSnapshot();
218
+ this.gauge("memory.heap.used", heap.heapUsed);
219
+ this.gauge("memory.heap.total", heap.heapTotal);
220
+ this.gauge("memory.heap.limit", heap.heapSizeLimit);
221
+ this.gauge("memory.heap.usage_percent", heap.usagePercent);
222
+ this.gauge("memory.rss", heap.rss);
223
+ this.gauge("memory.rss.usage_percent", rss.usagePercent);
224
+ }
225
+
226
+ get(name: string, labels?: Record<string, string>): MetricPoint | null {
227
+ const metric = this.metrics.get(name);
228
+ if (!metric) return null;
229
+ const key = labels ? JSON.stringify(labels) : "default";
230
+ return metric.values.get(key) || null;
231
+ }
232
+
233
+ formatPrometheus(): string {
234
+ let output = "";
235
+ for (const metric of this.metrics.values()) {
236
+ output += `# HELP ${metric.name} ${metric.help}\n`;
237
+ output += `# TYPE ${metric.name} ${metric.type}\n`;
238
+
239
+ for (const point of metric.values.values()) {
240
+ const labelPairs = point.labels
241
+ ? Object.entries(point.labels).map(([k, v]) => `${k}="${v}"`)
242
+ : [];
243
+ const labelsStr = labelPairs.length ? `{${labelPairs.join(",")}}` : "";
244
+
245
+ if (
246
+ metric.type === "histogram" &&
247
+ typeof point.value === "object" &&
248
+ point.value !== null
249
+ ) {
250
+ // Histogram points store a {count, sum, buckets} aggregate; emitting
251
+ // it raw produced "[object Object]" (invalid Prometheus exposition).
252
+ const data = point.value as {
253
+ count: number;
254
+ sum: number;
255
+ buckets: Map<number, number>;
256
+ };
257
+ const bucketPrefix = labelPairs.length
258
+ ? `${labelPairs.join(",")},`
259
+ : "";
260
+ const sortedBuckets = [...data.buckets.keys()].sort((a, b) => a - b);
261
+ for (const bucket of sortedBuckets) {
262
+ output += `${metric.name}_bucket{${bucketPrefix}le="${bucket}"} ${data.buckets.get(bucket)} ${point.timestamp}\n`;
263
+ }
264
+ output += `${metric.name}_bucket{${bucketPrefix}le="+Inf"} ${data.count} ${point.timestamp}\n`;
265
+ output += `${metric.name}_sum${labelsStr} ${data.sum} ${point.timestamp}\n`;
266
+ output += `${metric.name}_count${labelsStr} ${data.count} ${point.timestamp}\n`;
267
+ continue;
268
+ }
269
+
270
+ output += `${metric.name}${labelsStr} ${point.value} ${point.timestamp}\n`;
271
+ }
272
+ }
273
+ return output;
274
+ }
275
+
276
+ reset(): void {
277
+ for (const metric of this.metrics.values()) {
278
+ metric.values.clear();
279
+ }
280
+ this.emit("reset", {});
281
+ }
282
+
283
+ stopCollection(): void {
284
+ if (this.collectionInterval) {
285
+ clearInterval(this.collectionInterval);
286
+ this.collectionInterval = null;
287
+ }
288
+ }
289
+ }
290
+
291
+ export const metrics = new Metrics();
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Modo de raciocínio para modelos Qwen:
3
+ * - "auto": Qwen decide se usa thinking (padrão)
4
+ * - "thinking": força thinking ON
5
+ * - "fast": força thinking OFF
6
+ */
7
+ export type ReasoningMode = "auto" | "thinking" | "fast";
8
+
9
+ /**
10
+ * Resolução de variantes de raciocínio dos modelos Qwen públicos.
11
+ *
12
+ * Mapeamento padronizado de sufixos de esforço de raciocínio:
13
+ * - `-low`: força thinking OFF (Fast)
14
+ * - `-medium`: thinking AUTO (Qwen decide dinamicamente)
15
+ * - `-high`: força thinking ON (Thinking profundo)
16
+ *
17
+ * Sufixos legados (`-fast`, `-thinking`, `-no-thinking`) são mantidos
18
+ * para total compatibilidade regressiva. O modelo base limpo é sempre
19
+ * retornado para o upstream e publicado sem duplicatas em `/v1/models`.
20
+ */
21
+ export function stripThinkingSuffix(model: string): {
22
+ baseModel: string;
23
+ enableThinking: boolean;
24
+ reasoningMode: ReasoningMode;
25
+ } {
26
+ const normalizedModel = model.trim();
27
+
28
+ // Fast / Low path (thinking off)
29
+ if (
30
+ normalizedModel.endsWith("-low") ||
31
+ normalizedModel.endsWith("-fast") ||
32
+ normalizedModel.endsWith("-no-thinking")
33
+ ) {
34
+ return {
35
+ baseModel: normalizedModel.replace(/-(?:low|fast|no-thinking)$/, ""),
36
+ enableThinking: false,
37
+ reasoningMode: "fast",
38
+ };
39
+ }
40
+
41
+ // Medium path (auto thinking - Qwen decides dynamically)
42
+ if (normalizedModel.endsWith("-medium")) {
43
+ return {
44
+ baseModel: normalizedModel.slice(0, -"-medium".length),
45
+ enableThinking: true,
46
+ reasoningMode: "auto",
47
+ };
48
+ }
49
+
50
+ // High / Thinking path (thinking on)
51
+ if (
52
+ normalizedModel.endsWith("-high") ||
53
+ normalizedModel.endsWith("-thinking")
54
+ ) {
55
+ return {
56
+ baseModel: normalizedModel.replace(/-(?:high|thinking)$/, ""),
57
+ enableThinking: true,
58
+ reasoningMode: "thinking",
59
+ };
60
+ }
61
+
62
+ // Default: auto thinking (Qwen decides)
63
+ return { baseModel: normalizedModel, enableThinking: true, reasoningMode: "auto" };
64
+ }
65
+
66
+ /**
67
+ * Mapeia o id de modelo para o Qwen upstream.
68
+ * Ids `qwen*` passam direto (após remover o sufixo de raciocínio); ids de
69
+ * outros provedores (gpt-*, grok-*, etc.) também passam “as-is” — o Codex/Custom
70
+ * provider envia o id Qwen correto, e qualquer id desconhecido deve chegar ao
71
+ * upstream para que este responda um erro claro de modelo, em vez de ser
72
+ * silenciosamente roteado para um tier qualquer.
73
+ */
74
+ export function mapClientModelToQwen(model: string): string {
75
+ if (!model) return model;
76
+ return stripThinkingSuffix(model.trim()).baseModel;
77
+ }