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,326 +1,331 @@
1
- /**
2
- * QwenProxy TUI - Proxy Data Provider & Live State Client
3
- */
4
-
5
- import { config } from "../core/config.ts";
6
- import { loadAccounts, type QwenAccount } from "../core/accounts.ts";
7
- import {
8
- getAccountCooldownInfo,
9
- clearAllAccountCooldowns,
10
- clearAccountCooldown,
11
- isAccountHeadersReady,
12
- } from "../core/account-manager.ts";
13
- import { getAccountConcurrencySnapshot } from "../core/account-concurrency.ts";
14
- import { getRssUsageSnapshot } from "../core/memory-usage.ts";
15
- import type { ProxyStatusSnapshot } from "./types.ts";
16
-
17
- export function maskAccountIdentifier(idOrEmail: string): string {
18
- if (!idOrEmail) return "unknown";
19
- if (idOrEmail.includes("@")) {
20
- const [user, domain] = idOrEmail.split("@");
21
- const visible = user.slice(0, 2);
22
- return `${visible}***@${domain}`;
23
- }
24
-
25
- if (idOrEmail.length > 8) {
26
- return `${idOrEmail.slice(0, 3)}***${idOrEmail.slice(-3)}`;
27
- }
28
- return idOrEmail;
29
- }
30
-
31
- export function formatUptime(seconds: number): string {
32
- const hrs = Math.floor(seconds / 3600);
33
- const mins = Math.floor((seconds % 3600) / 60);
34
- const secs = Math.floor(seconds % 60);
35
- const pad2 = (n: number) => n.toString().padStart(2, "0");
36
- if (hrs > 0) {
37
- return `${pad2(hrs)}:${pad2(mins)}:${pad2(secs)}`;
38
- }
39
- return `${pad2(mins)}:${pad2(secs)}`;
40
- }
41
- let cachedAccounts: Array<{
42
- id: string;
43
- emailOrName: string;
44
- priority: number;
45
- cooldownUntil: number | null;
46
- onCooldown: boolean;
47
- remainingCooldownMs: number;
48
- headersReady: boolean;
49
- }> = [];
50
- let lastAccountsFetch = 0;
51
- let isHealthCheckPending = false;
52
- let lastOnlineState = false;
53
- let lastOverallStatus = "offline";
54
-
55
- export async function fetchProxyStatus(): Promise<ProxyStatusSnapshot> {
56
- const port = config.server?.port || 7936;
57
- const configuredHost = config.server?.host;
58
- const host = configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1";
59
- const uptimeSeconds = Math.floor(process.uptime());
60
-
61
- // Fast non-blocking health probe
62
- if (!isHealthCheckPending) {
63
- isHealthCheckPending = true;
64
- const controller = new AbortController();
65
- const timeout = setTimeout(() => controller.abort(), 350);
66
- fetch(`http://${host}:${port}/health`, { signal: controller.signal })
67
- .then(async (resp) => {
68
- clearTimeout(timeout);
69
- if (resp.ok) {
70
- lastOnlineState = true;
71
- const data = (await resp.json()) as any;
72
- lastOverallStatus = data.status || "healthy";
73
- } else {
74
- lastOnlineState = false;
75
- }
76
- })
77
- .catch(() => {
78
- clearTimeout(timeout);
79
- lastOnlineState = false;
80
- })
81
- .finally(() => {
82
- isHealthCheckPending = false;
83
- });
84
- }
85
-
86
- const now = Date.now();
87
- if (now - lastAccountsFetch > 3000 || cachedAccounts.length === 0) {
88
- lastAccountsFetch = now;
89
- let rawAccounts: QwenAccount[] = [];
90
- try {
91
- rawAccounts = loadAccounts();
92
- } catch {
93
- rawAccounts = [];
94
- }
95
-
96
- cachedAccounts = rawAccounts.map((acc) => {
97
- const cooldownInfo = getAccountCooldownInfo(acc.id);
98
- const onCooldown = Boolean(cooldownInfo?.onCooldown);
99
- const remainingCooldownMs = cooldownInfo?.remainingMs || 0;
100
- const headersReady = isAccountHeadersReady(acc.id);
101
-
102
- return {
103
- id: acc.id,
104
- emailOrName: maskAccountIdentifier(acc.email || acc.id),
105
- priority: 1,
106
- cooldownUntil: acc.cooldown_until || null,
107
- onCooldown,
108
- remainingCooldownMs,
109
- headersReady,
110
- };
111
- });
112
- }
113
-
114
- const accounts = cachedAccounts;
115
- const online = lastOnlineState;
116
- const overallStatus = lastOverallStatus;
117
-
118
- // Concurrency stats
119
- let activeStreams = 0;
120
- let waitingStreams = 0;
121
- try {
122
- const snapshot = getAccountConcurrencySnapshot();
123
- for (const item of snapshot) {
124
- activeStreams += item.active;
125
- waitingStreams += item.waiting;
126
- }
127
- } catch {}
128
-
129
- // RAM usage
130
- let rssMb = 0;
131
- let systemMemoryPct = 0;
132
- try {
133
- const rssSnap = getRssUsageSnapshot();
134
- rssMb = Math.round(rssSnap.rss / (1024 * 1024));
135
- systemMemoryPct = Math.round(rssSnap.usagePercent * 10) / 10;
136
- } catch {}
137
-
138
- return {
139
- online,
140
- port,
141
- host,
142
- overallStatus,
143
- uptimeSeconds,
144
- rssMb,
145
- systemMemoryPct,
146
- activeStreams,
147
- waitingStreams,
148
- accounts,
149
- };
150
- }
151
-
152
- export function resetAllCooldowns(): number {
153
- return clearAllAccountCooldowns();
154
- }
155
-
156
- export function resetAccountCooldownById(accountId: string): void {
157
- clearAccountCooldown(accountId);
158
- }
159
-
160
- export interface StreamChatOptions {
161
- model: string;
162
- reasoning_effort?: "low" | "medium" | "high";
163
- messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
164
- onToken: (text: string) => void;
165
- onReasoning?: (text: string) => void;
166
- signal?: AbortSignal;
167
- }
168
-
169
- /**
170
- * Streams a chat completion response from the local proxy endpoint.
171
- */
172
- export async function streamChatCompletions(
173
- options: StreamChatOptions,
174
- ): Promise<{ totalTimeMs: number; ttfbMs: number }> {
175
- const port = config.server?.port || 7936;
176
- const configuredHost = config.server?.host;
177
- const host = configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1";
178
- const apiKey = config.apiKey || "sk-qwenproxy-local";
179
-
180
- const startTime = Date.now();
181
- let ttfbMs = 0;
182
-
183
- let resp: Response;
184
- try {
185
- resp = await fetch(`http://${host}:${port}/v1/chat/completions`, {
186
- method: "POST",
187
- headers: {
188
- "Content-Type": "application/json",
189
- Authorization: `Bearer ${apiKey}`,
190
- },
191
- body: JSON.stringify({
192
- model: options.model,
193
- reasoning_effort: options.reasoning_effort,
194
- messages: options.messages,
195
- stream: true,
196
- }),
197
- signal: options.signal,
198
- });
199
- } catch (fetchErr: any) {
200
- if (fetchErr?.name === "AbortError" || options.signal?.aborted) {
201
- throw fetchErr;
202
- }
203
- throw new Error(
204
- `O servidor QwenProxy está iniciando ou indisponível (:7936). Verifique o status ou a aba [6] Logs.`,
205
- );
206
- }
207
-
208
- if (!resp.ok) {
209
- const errText = await resp.text();
210
- throw new Error(`HTTP ${resp.status}: ${errText}`);
211
- }
212
-
213
- if (!resp.body) {
214
- throw new Error("No response body received from proxy");
215
- }
216
-
217
- const reader = resp.body.getReader();
218
- const decoder = new TextDecoder();
219
- let buffer = "";
220
-
221
- while (true) {
222
- const { done, value } = await reader.read();
223
- if (done) break;
224
-
225
- if (ttfbMs === 0) {
226
- ttfbMs = Date.now() - startTime;
227
- }
228
-
229
- buffer += decoder.decode(value, { stream: true });
230
- const lines = buffer.split("\n");
231
- buffer = lines.pop() || "";
232
-
233
- for (const line of lines) {
234
- const trimmed = line.trim();
235
- if (!trimmed.startsWith("data:")) continue;
236
- const dataStr = trimmed.replace(/^data:\s*/, "").trim();
237
- if (dataStr === "[DONE]") break;
238
-
239
- try {
240
- const parsed = JSON.parse(dataStr);
241
- const delta = parsed.choices?.[0]?.delta;
242
- if (!delta) continue;
243
-
244
- if (delta.reasoning_content && options.onReasoning) {
245
- options.onReasoning(delta.reasoning_content);
246
- }
247
- if (delta.content) {
248
- options.onToken(delta.content);
249
- }
250
- } catch {}
251
- }
252
- }
253
-
254
- return {
255
- totalTimeMs: Date.now() - startTime,
256
- ttfbMs: ttfbMs || Date.now() - startTime,
257
- };
258
- }
259
-
260
- /**
261
- * Fetches all live models dynamically from the running proxy /v1/models catalog.
262
- */
263
- let cachedLiveModels: string[] | null = null;
264
- let isFetchingLiveModels = false;
265
-
266
- export async function fetchLiveModels(): Promise<string[]> {
267
- if (cachedLiveModels && cachedLiveModels.length > 0) {
268
- return cachedLiveModels;
269
- }
270
-
271
- const port = config.server?.port || 7936;
272
- const configuredHost = config.server?.host;
273
- const host = configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1";
274
- const apiKey = config.apiKey || "sk-qwenproxy-local";
275
-
276
- if (!isFetchingLiveModels) {
277
- isFetchingLiveModels = true;
278
- const controller = new AbortController();
279
- const timeout = setTimeout(() => controller.abort(), 2500);
280
- fetch(`http://${host}:${port}/v1/models`, {
281
- headers: { Authorization: `Bearer ${apiKey}` },
282
- signal: controller.signal,
283
- })
284
- .then(async (resp) => {
285
- clearTimeout(timeout);
286
- if (resp.ok) {
287
- const json = (await resp.json()) as any;
288
- if (Array.isArray(json?.data)) {
289
- const models = json.data
290
- .map((m: any) => m.id)
291
- .filter((id: any): id is string => typeof id === "string" && id.trim().length > 0)
292
- .filter(
293
- (id: string) =>
294
- !id.endsWith("-fast") &&
295
- !id.endsWith("-thinking") &&
296
- !id.endsWith("-no-thinking"),
297
- );
298
- if (models.length > 0) {
299
- cachedLiveModels = Array.from(new Set(models));
300
- }
301
- }
302
- }
303
- })
304
- .catch(() => {
305
- clearTimeout(timeout);
306
- })
307
- .finally(() => {
308
- isFetchingLiveModels = false;
309
- });
310
- }
311
-
312
- return (
313
- cachedLiveModels || [
314
- "qwen3.8-max",
315
- "qwen3.7-plus",
316
- "qwen3.7-max",
317
- "z-image-turbo",
318
- "qwen-image-3.0-pro",
319
- "qwen-image-3.0",
320
- "wan2.7-image-pro",
321
- "wan2.7-image",
322
- "wan3.0-video",
323
- "wan2.7-t2v",
324
- ]
325
- );
326
- }
1
+ /**
2
+ * QwenProxy TUI - Proxy Data Provider & Live State Client
3
+ */
4
+
5
+ import { config } from "../core/config.ts";
6
+ import { loadAccounts, type QwenAccount } from "../core/accounts.ts";
7
+ import {
8
+ getAccountCooldownInfo,
9
+ clearAllAccountCooldowns,
10
+ clearAccountCooldown,
11
+ isAccountHeadersReady,
12
+ } from "../core/account-manager.ts";
13
+ import { getAccountConcurrencySnapshot } from "../core/account-concurrency.ts";
14
+ import { getRssUsageSnapshot } from "../core/memory-usage.ts";
15
+ import type { ProxyStatusSnapshot } from "./types.ts";
16
+
17
+ export function maskAccountIdentifier(idOrEmail: string): string {
18
+ if (!idOrEmail) return "unknown";
19
+ if (idOrEmail.includes("@")) {
20
+ const [user, domain] = idOrEmail.split("@");
21
+ const visible = user.slice(0, 2);
22
+ return `${visible}***@${domain}`;
23
+ }
24
+
25
+ if (idOrEmail.length > 8) {
26
+ return `${idOrEmail.slice(0, 3)}***${idOrEmail.slice(-3)}`;
27
+ }
28
+ return idOrEmail;
29
+ }
30
+
31
+ export function formatUptime(seconds: number): string {
32
+ const hrs = Math.floor(seconds / 3600);
33
+ const mins = Math.floor((seconds % 3600) / 60);
34
+ const secs = Math.floor(seconds % 60);
35
+ const pad2 = (n: number) => n.toString().padStart(2, "0");
36
+ if (hrs > 0) {
37
+ return `${pad2(hrs)}:${pad2(mins)}:${pad2(secs)}`;
38
+ }
39
+ return `${pad2(mins)}:${pad2(secs)}`;
40
+ }
41
+ let cachedAccounts: Array<{
42
+ id: string;
43
+ emailOrName: string;
44
+ priority: number;
45
+ cooldownUntil: number | null;
46
+ onCooldown: boolean;
47
+ remainingCooldownMs: number;
48
+ headersReady: boolean;
49
+ }> = [];
50
+ let lastAccountsFetch = 0;
51
+ let isHealthCheckPending = false;
52
+ let lastOnlineState = false;
53
+ let lastOverallStatus = "offline";
54
+ let lastServerReadyAccounts: Set<string> | null = null;
55
+ export async function fetchProxyStatus(): Promise<ProxyStatusSnapshot> {
56
+ const port = config.server?.port || 7936;
57
+ const configuredHost = config.server?.host;
58
+ const host = configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1";
59
+ const uptimeSeconds = Math.floor(process.uptime());
60
+
61
+ // Fast non-blocking health probe
62
+ if (!isHealthCheckPending) {
63
+ isHealthCheckPending = true;
64
+ const controller = new AbortController();
65
+ const timeout = setTimeout(() => controller.abort(), 350);
66
+ fetch(`http://${host}:${port}/health`, { signal: controller.signal })
67
+ .then(async (resp) => {
68
+ clearTimeout(timeout);
69
+ if (resp.ok) {
70
+ lastOnlineState = true;
71
+ const data = (await resp.json()) as any;
72
+ lastOverallStatus = data.status || "healthy";
73
+ if (Array.isArray(data.readyAccounts)) {
74
+ lastServerReadyAccounts = new Set(data.readyAccounts);
75
+ }
76
+ } else {
77
+ lastOnlineState = false;
78
+ lastServerReadyAccounts = null;
79
+ }
80
+ })
81
+ .catch(() => {
82
+ clearTimeout(timeout);
83
+ lastOnlineState = false;
84
+ })
85
+ .finally(() => {
86
+ isHealthCheckPending = false;
87
+ });
88
+ }
89
+
90
+ const now = Date.now();
91
+ if (now - lastAccountsFetch > 3000 || cachedAccounts.length === 0) {
92
+ lastAccountsFetch = now;
93
+ let rawAccounts: QwenAccount[] = [];
94
+ try {
95
+ rawAccounts = loadAccounts();
96
+ } catch {
97
+ rawAccounts = [];
98
+ }
99
+
100
+ cachedAccounts = rawAccounts.map((acc) => {
101
+ const cooldownInfo = getAccountCooldownInfo(acc.id);
102
+ const onCooldown = Boolean(cooldownInfo?.onCooldown);
103
+ const remainingCooldownMs = cooldownInfo?.remainingMs || 0;
104
+ const headersReady = lastServerReadyAccounts !== null
105
+ ? lastServerReadyAccounts.has(acc.id)
106
+ : isAccountHeadersReady(acc.id);
107
+ return {
108
+ id: acc.id,
109
+ emailOrName: maskAccountIdentifier(acc.email || acc.id),
110
+ priority: 1,
111
+ cooldownUntil: acc.cooldown_until || null,
112
+ onCooldown,
113
+ remainingCooldownMs,
114
+ headersReady,
115
+ };
116
+ });
117
+ }
118
+
119
+ const accounts = cachedAccounts;
120
+ const online = lastOnlineState;
121
+ const overallStatus = lastOverallStatus;
122
+
123
+ // Concurrency stats
124
+ let activeStreams = 0;
125
+ let waitingStreams = 0;
126
+ try {
127
+ const snapshot = getAccountConcurrencySnapshot();
128
+ for (const item of snapshot) {
129
+ activeStreams += item.active;
130
+ waitingStreams += item.waiting;
131
+ }
132
+ } catch {}
133
+
134
+ // RAM usage
135
+ let rssMb = 0;
136
+ let systemMemoryPct = 0;
137
+ try {
138
+ const rssSnap = getRssUsageSnapshot();
139
+ rssMb = Math.round(rssSnap.rss / (1024 * 1024));
140
+ systemMemoryPct = Math.round(rssSnap.usagePercent * 10) / 10;
141
+ } catch {}
142
+
143
+ return {
144
+ online,
145
+ port,
146
+ host,
147
+ overallStatus,
148
+ uptimeSeconds,
149
+ rssMb,
150
+ systemMemoryPct,
151
+ activeStreams,
152
+ waitingStreams,
153
+ accounts,
154
+ };
155
+ }
156
+
157
+ export function resetAllCooldowns(): number {
158
+ return clearAllAccountCooldowns();
159
+ }
160
+
161
+ export function resetAccountCooldownById(accountId: string): void {
162
+ clearAccountCooldown(accountId);
163
+ }
164
+
165
+ export interface StreamChatOptions {
166
+ model: string;
167
+ reasoning_effort?: "low" | "medium" | "high";
168
+ messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
169
+ onToken: (text: string) => void;
170
+ onReasoning?: (text: string) => void;
171
+ signal?: AbortSignal;
172
+ }
173
+
174
+ /**
175
+ * Streams a chat completion response from the local proxy endpoint.
176
+ */
177
+ export async function streamChatCompletions(
178
+ options: StreamChatOptions,
179
+ ): Promise<{ totalTimeMs: number; ttfbMs: number }> {
180
+ const port = config.server?.port || 7936;
181
+ const configuredHost = config.server?.host;
182
+ const host = configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1";
183
+ const apiKey = config.apiKey || "sk-qwenproxy-local";
184
+
185
+ const startTime = Date.now();
186
+ let ttfbMs = 0;
187
+
188
+ let resp: Response;
189
+ try {
190
+ resp = await fetch(`http://${host}:${port}/v1/chat/completions`, {
191
+ method: "POST",
192
+ headers: {
193
+ "Content-Type": "application/json",
194
+ Authorization: `Bearer ${apiKey}`,
195
+ },
196
+ body: JSON.stringify({
197
+ model: options.model,
198
+ reasoning_effort: options.reasoning_effort,
199
+ messages: options.messages,
200
+ stream: true,
201
+ }),
202
+ signal: options.signal,
203
+ });
204
+ } catch (fetchErr: any) {
205
+ if (fetchErr?.name === "AbortError" || options.signal?.aborted) {
206
+ throw fetchErr;
207
+ }
208
+ throw new Error(
209
+ `O servidor QwenProxy está iniciando ou indisponível (:7936). Verifique o status ou a aba [6] Logs.`,
210
+ );
211
+ }
212
+
213
+ if (!resp.ok) {
214
+ const errText = await resp.text();
215
+ throw new Error(`HTTP ${resp.status}: ${errText}`);
216
+ }
217
+
218
+ if (!resp.body) {
219
+ throw new Error("No response body received from proxy");
220
+ }
221
+
222
+ const reader = resp.body.getReader();
223
+ const decoder = new TextDecoder();
224
+ let buffer = "";
225
+
226
+ while (true) {
227
+ const { done, value } = await reader.read();
228
+ if (done) break;
229
+
230
+ if (ttfbMs === 0) {
231
+ ttfbMs = Date.now() - startTime;
232
+ }
233
+
234
+ buffer += decoder.decode(value, { stream: true });
235
+ const lines = buffer.split("\n");
236
+ buffer = lines.pop() || "";
237
+
238
+ for (const line of lines) {
239
+ const trimmed = line.trim();
240
+ if (!trimmed.startsWith("data:")) continue;
241
+ const dataStr = trimmed.replace(/^data:\s*/, "").trim();
242
+ if (dataStr === "[DONE]") break;
243
+
244
+ try {
245
+ const parsed = JSON.parse(dataStr);
246
+ const delta = parsed.choices?.[0]?.delta;
247
+ if (!delta) continue;
248
+
249
+ if (delta.reasoning_content && options.onReasoning) {
250
+ options.onReasoning(delta.reasoning_content);
251
+ }
252
+ if (delta.content) {
253
+ options.onToken(delta.content);
254
+ }
255
+ } catch {}
256
+ }
257
+ }
258
+
259
+ return {
260
+ totalTimeMs: Date.now() - startTime,
261
+ ttfbMs: ttfbMs || Date.now() - startTime,
262
+ };
263
+ }
264
+
265
+ /**
266
+ * Fetches all live models dynamically from the running proxy /v1/models catalog.
267
+ */
268
+ let cachedLiveModels: string[] | null = null;
269
+ let isFetchingLiveModels = false;
270
+
271
+ export async function fetchLiveModels(): Promise<string[]> {
272
+ if (cachedLiveModels && cachedLiveModels.length > 0) {
273
+ return cachedLiveModels;
274
+ }
275
+
276
+ const port = config.server?.port || 7936;
277
+ const configuredHost = config.server?.host;
278
+ const host = configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1";
279
+ const apiKey = config.apiKey || "sk-qwenproxy-local";
280
+
281
+ if (!isFetchingLiveModels) {
282
+ isFetchingLiveModels = true;
283
+ const controller = new AbortController();
284
+ const timeout = setTimeout(() => controller.abort(), 2500);
285
+ fetch(`http://${host}:${port}/v1/models`, {
286
+ headers: { Authorization: `Bearer ${apiKey}` },
287
+ signal: controller.signal,
288
+ })
289
+ .then(async (resp) => {
290
+ clearTimeout(timeout);
291
+ if (resp.ok) {
292
+ const json = (await resp.json()) as any;
293
+ if (Array.isArray(json?.data)) {
294
+ const models = json.data
295
+ .map((m: any) => m.id)
296
+ .filter((id: any): id is string => typeof id === "string" && id.trim().length > 0)
297
+ .filter(
298
+ (id: string) =>
299
+ !id.endsWith("-fast") &&
300
+ !id.endsWith("-thinking") &&
301
+ !id.endsWith("-no-thinking"),
302
+ );
303
+ if (models.length > 0) {
304
+ cachedLiveModels = Array.from(new Set(models));
305
+ }
306
+ }
307
+ }
308
+ })
309
+ .catch(() => {
310
+ clearTimeout(timeout);
311
+ })
312
+ .finally(() => {
313
+ isFetchingLiveModels = false;
314
+ });
315
+ }
316
+
317
+ return (
318
+ cachedLiveModels || [
319
+ "qwen3.8-max",
320
+ "qwen3.7-plus",
321
+ "qwen3.7-max",
322
+ "z-image-turbo",
323
+ "qwen-image-3.0-pro",
324
+ "qwen-image-3.0",
325
+ "wan2.7-image-pro",
326
+ "wan2.7-image",
327
+ "wan3.0-video",
328
+ "wan2.7-t2v",
329
+ ]
330
+ );
331
+ }