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,258 @@
1
+ /**
2
+ * QwenProxy TUI - Lightweight Terminal Markdown Formatter
3
+ * Formats Markdown bold, italic, code blocks, bullet lists, and headers into ANSI styles
4
+ * with word-wrapping that respects terminal column constraints.
5
+ */
6
+
7
+ import { theme, stringWidth } from "./theme.ts";
8
+ export interface MarkdownOptions {
9
+ dim?: boolean;
10
+ }
11
+
12
+ /**
13
+ * Formats Qwen's internal reasoning into a uniform, subdued, all-italic monologue.
14
+ * Strips distracting markdown formatting and keeps every thought in a homogeneous opaque tone.
15
+ */
16
+ export function formatReasoning(content: string, maxWidth: number): string[] {
17
+ const rawLines = content.split("\n");
18
+ const result: string[] = [];
19
+ const dimItalic = (s: string) => `\x1b[3m\x1b[38;2;120;125;145m${s}\x1b[39m\x1b[23m`;
20
+
21
+ for (const raw of rawLines) {
22
+ const trimmed = raw.trimEnd();
23
+ if (!trimmed) {
24
+ result.push("");
25
+ continue;
26
+ }
27
+ // Strip markdown asterisks and backticks so thoughts don't have clashing colors
28
+ const cleanText = trimmed
29
+ .replace(/(\*\*|__)(.*?)\1/g, "$2")
30
+ .replace(/`([^`]+)`/g, "$1")
31
+ .replace(/^#+\s*/, "");
32
+
33
+ const wrapped = wrapAnsiLine(cleanText, maxWidth);
34
+ for (const w of wrapped) {
35
+ result.push(dimItalic(w));
36
+ }
37
+ }
38
+ return result;
39
+ }
40
+
41
+
42
+ /**
43
+ * Renders an elegant OSC 8 interactive card for images generated by Qwen.
44
+ */
45
+ export function formatImageCard(alt: string, url: string, maxWidth: number): string[] {
46
+ const cardW = Math.max(30, Math.min(maxWidth, 70));
47
+ const cleanAlt =
48
+ alt && alt !== "Generated image" && alt !== "image"
49
+ ? ` ${alt.trim()} `
50
+ : " Imagem Gerada ";
51
+ const innerW = cardW - 2;
52
+ const linkLabel = `[ 🔗 Clique para abrir a imagem no navegador ]`;
53
+ const osc8 = `\x1b]8;;${url}\x1b\\${theme.cyan(theme.underline(linkLabel))}\x1b]8;;\x1b\\`;
54
+ const labelVisualW = stringWidth(linkLabel);
55
+ const paddingRight = " ".repeat(Math.max(0, innerW - labelVisualW - 2));
56
+
57
+ const titleW = stringWidth(cleanAlt);
58
+ const topHr = "─".repeat(Math.max(2, innerW - titleW - 5));
59
+ const bottomHr = "─".repeat(innerW);
60
+
61
+ return [
62
+ ` ${theme.borderActive(`╭─ 🖼️ ${cleanAlt}${topHr}╮`)}`,
63
+ ` ${theme.borderActive("│")} ${osc8}${paddingRight}${theme.borderActive("│")}`,
64
+ ` ${theme.borderActive(`╰${bottomHr}╯`)}`,
65
+ ];
66
+ }
67
+ /**
68
+ * Formats inline Markdown elements (bold, italic, code, strikethrough).
69
+ */
70
+ export function formatMarkdownInline(text: string, options?: MarkdownOptions): string {
71
+ const dim = options?.dim ?? false;
72
+ let res = text;
73
+
74
+ if (dim) {
75
+ const muted = "\x1b[38;2;120;125;145m";
76
+ const reset = "\x1b[39m";
77
+ // Uniform dimmed italic mode
78
+ res = res.replace(/(\*\*|__)(.*?)\1/g, (_m, _d, content) => `\x1b[3m${content}\x1b[23m`);
79
+ res = res.replace(/(?<!\w)(\*|_)(.*?)\1(?!\w)/g, (_m, _d, content) => `\x1b[3m${content}\x1b[23m`);
80
+ res = res.replace(/`([^`]+)`/g, (_m, content) => `\x1b[3m${content}\x1b[23m`);
81
+ res = res.replace(/~~(.*?)~~/g, (_m, content) => `\x1b[9m${content}\x1b[29m`);
82
+ return `\x1b[3m${muted}${res}${reset}\x1b[23m`;
83
+ }
84
+
85
+ // Standard vibrant TrueColor mode (for assistant final responses)
86
+ res = res.replace(/(\*\*|__)(.*?)\1/g, (_m, _d, content) => theme.bold(theme.white(content)));
87
+ res = res.replace(/(?<!\w)(\*|_)(.*?)\1(?!\w)/g, (_m, _d, content) =>
88
+ theme.italic(theme.lavender(content)),
89
+ );
90
+ res = res.replace(/`([^`]+)`/g, (_m, content) => theme.cyan(content));
91
+ res = res.replace(/~~(.*?)~~/g, (_m, content) => `\x1b[9m${content}\x1b[29m`);
92
+
93
+ return res;
94
+ }
95
+
96
+ /**
97
+ * Word-wraps a single ANSI-styled string into multiple lines without breaking ANSI sequences.
98
+ */
99
+ export function wrapAnsiLine(line: string, maxWidth: number): string[] {
100
+ if (maxWidth <= 0) return [line];
101
+ if (stringWidth(line) <= maxWidth) return [line];
102
+
103
+ const words = line.split(" ");
104
+ const lines: string[] = [];
105
+ let currentLine = "";
106
+
107
+ for (const word of words) {
108
+ const testLine = currentLine ? `${currentLine} ${word}` : word;
109
+ if (stringWidth(testLine) <= maxWidth) {
110
+ currentLine = testLine;
111
+ } else {
112
+ if (currentLine) lines.push(currentLine);
113
+ currentLine = word;
114
+ }
115
+ }
116
+
117
+ if (currentLine) lines.push(currentLine);
118
+ return lines.length > 0 ? lines : [""];
119
+ }
120
+
121
+ /**
122
+ * Parses full multi-line Markdown text and returns an array of formatted, word-wrapped lines.
123
+ */
124
+ export function formatMarkdown(
125
+ content: string,
126
+ maxWidth: number,
127
+ options?: MarkdownOptions,
128
+ ): string[] {
129
+ const rawLines = content.split("\n");
130
+ const result: string[] = [];
131
+ let inCodeBlock = false;
132
+ const isDim = options?.dim ?? false;
133
+
134
+ for (const rawLine of rawLines) {
135
+ const trimmed = rawLine.trimEnd();
136
+
137
+ // Image Markdown: ![alt](url)
138
+ const imgRegex = /!\[(.*?)\]\((https?:\/\/[^\s)]+)\)/g;
139
+ if (imgRegex.test(trimmed)) {
140
+ const parts = trimmed.split(/(!\[.*?\]\(https?:\/\/[^\s)]+\))/g);
141
+ for (const part of parts) {
142
+ const m = part.match(/^!\[(.*?)\]\((https?:\/\/[^\s)]+)\)$/);
143
+ if (m) {
144
+ result.push(...formatImageCard(m[1], m[2], maxWidth));
145
+ } else if (part.trim()) {
146
+ const inlineFormatted = formatMarkdownInline(part.trim(), options);
147
+ result.push(...wrapAnsiLine(inlineFormatted, maxWidth));
148
+ }
149
+ }
150
+ continue;
151
+ }
152
+
153
+ // Code blocks: ```lang ... ```
154
+ if (trimmed.startsWith("```")) {
155
+ inCodeBlock = !inCodeBlock;
156
+ const lang = trimmed.slice(3).trim();
157
+ if (inCodeBlock) {
158
+ const border = isDim ? theme.dark : theme.blue;
159
+ result.push(border(`┌─── ${lang || "code"} ───────────────────────────`));
160
+ } else {
161
+ const border = isDim ? theme.dark : theme.blue;
162
+ result.push(border("└───"));
163
+ }
164
+ continue;
165
+ }
166
+
167
+ if (inCodeBlock) {
168
+ if (isDim) {
169
+ result.push(theme.dark(`│ `) + theme.muted(trimmed));
170
+ } else {
171
+ result.push(theme.blue(`│ `) + theme.cyan(trimmed));
172
+ }
173
+ continue;
174
+ }
175
+
176
+ // Headers
177
+ if (/^#{1,3}\s+/.test(trimmed)) {
178
+ const level = trimmed.match(/^#+/)?.[0].length || 1;
179
+ const cleanHeader = trimmed.replace(/^#+\s*/, "");
180
+ const formattedHeader = formatMarkdownInline(cleanHeader, options);
181
+ if (isDim) {
182
+ result.push(theme.bold(theme.muted(`■ ${cleanHeader}`)));
183
+ } else {
184
+ if (level === 1) {
185
+ result.push(theme.bold(theme.lavender(`■ ${formattedHeader}`)));
186
+ } else if (level === 2) {
187
+ result.push(theme.bold(theme.blue(`● ${formattedHeader}`)));
188
+ } else {
189
+ result.push(theme.bold(theme.cyan(`▸ ${formattedHeader}`)));
190
+ }
191
+ }
192
+ continue;
193
+ }
194
+
195
+ // Blockquotes
196
+ if (trimmed.startsWith(">")) {
197
+ const quoteText = trimmed.replace(/^>\s*/, "");
198
+ const formattedQuote = formatMarkdownInline(quoteText, options);
199
+ const wrapped = wrapAnsiLine(formattedQuote, Math.max(10, maxWidth - 4));
200
+ for (const wl of wrapped) {
201
+ result.push(theme.muted("│ ") + theme.italic(wl));
202
+ }
203
+ continue;
204
+ }
205
+
206
+ // Bullet lists (- or * or •)
207
+ if (/^(\s*)[-*•]\s+/.test(trimmed)) {
208
+ const match = trimmed.match(/^(\s*)[-*•]\s+(.*)$/);
209
+ if (match) {
210
+ const indent = match[1] || "";
211
+ const itemText = formatMarkdownInline(match[2], options);
212
+ const wrapped = wrapAnsiLine(itemText, Math.max(10, maxWidth - indent.length - 4));
213
+ const bullet = isDim ? theme.dark("•") : theme.cyan("•");
214
+ wrapped.forEach((wl, idx) => {
215
+ if (idx === 0) {
216
+ result.push(`${indent} ${bullet} ${wl}`);
217
+ } else {
218
+ result.push(`${indent} ${wl}`);
219
+ }
220
+ });
221
+ continue;
222
+ }
223
+ }
224
+
225
+ // Numbered lists (1. 2.)
226
+ if (/^(\s*)\d+\.\s+/.test(trimmed)) {
227
+ const match = trimmed.match(/^(\s*)(\d+\.)\s+(.*)$/);
228
+ if (match) {
229
+ const indent = match[1] || "";
230
+ const num = match[2];
231
+ const itemText = formatMarkdownInline(match[3], options);
232
+ const wrapped = wrapAnsiLine(itemText, Math.max(10, maxWidth - indent.length - num.length - 3));
233
+ const numStyled = isDim ? theme.muted(num) : theme.blue(num);
234
+ wrapped.forEach((wl, idx) => {
235
+ if (idx === 0) {
236
+ result.push(`${indent} ${numStyled} ${wl}`);
237
+ } else {
238
+ result.push(`${indent} ${wl}`);
239
+ }
240
+ });
241
+ continue;
242
+ }
243
+ }
244
+
245
+ // Empty lines
246
+ if (!trimmed) {
247
+ result.push("");
248
+ continue;
249
+ }
250
+
251
+ // Standard paragraph with inline formatting and word-wrap
252
+ const inlineFormatted = formatMarkdownInline(trimmed, options);
253
+ const wrapped = wrapAnsiLine(inlineFormatted, maxWidth);
254
+ result.push(...wrapped);
255
+ }
256
+
257
+ return result;
258
+ }
@@ -0,0 +1,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
+
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
+ }