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,285 @@
1
+ /**
2
+ * Native image/video generation over /v1/chat/completions. When the client
3
+ * selects a generation-specific model (qwen-image-*, wan2.*), the request is
4
+ * routed here instead of the text chat flow, mirroring how the Qwen web app
5
+ * switches chat_type to t2i/t2v. The media URL is returned as the assistant
6
+ * message content in a standard chat.completion / chat.completion.chunk.
7
+ */
8
+
9
+ import type { Context } from "hono";
10
+ import { stream as honoStream } from "hono/streaming";
11
+ import type { OpenAIRequest } from "../../utils/types.ts";
12
+ import {
13
+ generateImage,
14
+ generateVideo,
15
+ isSupportedMediaSize,
16
+ MEDIA_SIZE_OPTIONS,
17
+ logMediaError,
18
+ logMediaInfo,
19
+ mediaLog,
20
+ supportsPromptMediaGeneration,
21
+ } from "../../services/media-generation.ts";
22
+ import { sendOpenAIError } from "../../api/error-helpers.ts";
23
+ import { ValidationError } from "../../core/errors.ts";
24
+
25
+
26
+ const IMAGE_DEFAULT_SIZE = "auto";
27
+ const VIDEO_DEFAULT_SIZE = "16:9";
28
+ const STREAM_HEARTBEAT_MS = 15_000;
29
+
30
+ interface MediaChatParams {
31
+ c: Context;
32
+ body: OpenAIRequest;
33
+ model: string;
34
+ kind: "image" | "video";
35
+ isStream: boolean;
36
+ }
37
+
38
+ /**
39
+ * Chatbox renders Markdown images but not HTML/video nodes. Keep the video
40
+ * response portable as a clickable Markdown link; the browser can play the
41
+ * MP4 when the link is opened.
42
+ */
43
+ export function formatGeneratedVideoContent(videoUrl: string): string {
44
+ return `[🎬 Generated video](${videoUrl})`;
45
+ }
46
+
47
+ /**
48
+ * Extracts the generation prompt from the last user message. Accepts both
49
+ * plain-string content and multimodal arrays (using the text parts).
50
+ */
51
+ function extractPrompt(body: OpenAIRequest): string {
52
+ const messages = Array.isArray(body.messages) ? body.messages : [];
53
+ for (let i = messages.length - 1; i >= 0; i--) {
54
+ const msg = messages[i] as { role?: string; content?: unknown };
55
+ if (msg.role !== "user") continue;
56
+ const content = msg.content;
57
+ if (typeof content === "string") {
58
+ const trimmed = content.trim();
59
+ if (trimmed) return trimmed;
60
+ continue;
61
+ }
62
+ if (Array.isArray(content)) {
63
+ const text = (content as Array<{ type?: string; text?: unknown }>)
64
+ .filter((part) => part?.type === "text")
65
+ .map((part) => (typeof part.text === "string" ? part.text : ""))
66
+ .join("\n")
67
+ .trim();
68
+ if (text) return text;
69
+ }
70
+ }
71
+ return "";
72
+ }
73
+
74
+ function estimatePromptTokens(prompt: string): number {
75
+ return Math.max(1, Math.ceil(prompt.length / 4));
76
+ }
77
+
78
+ function makeCompletionId(): string {
79
+ return `chatcmpl-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
80
+ }
81
+
82
+ export async function handleMediaChatCompletion(
83
+ params: MediaChatParams,
84
+ ): Promise<Response> {
85
+ const { c, body, model, kind, isStream } = params;
86
+
87
+ const prompt = extractPrompt(body);
88
+ if (!prompt) {
89
+ const err = new ValidationError(
90
+ "The last user message must contain a non-empty prompt for media generation",
91
+ );
92
+ err.param = "messages";
93
+ return sendOpenAIError(c, err);
94
+ }
95
+
96
+ if (!supportsPromptMediaGeneration(model, kind)) {
97
+ const err = new ValidationError(
98
+ `Model \`${model}\` requires a reference image and is not available through prompt-only chat generation yet`,
99
+ );
100
+ err.param = "model";
101
+ return sendOpenAIError(c, err);
102
+ }
103
+
104
+ const requestedSize = body.size;
105
+ if (
106
+ requestedSize !== undefined &&
107
+ !isSupportedMediaSize(requestedSize)
108
+ ) {
109
+ const err = new ValidationError(
110
+ `\`size\` must be one of: ${MEDIA_SIZE_OPTIONS.join(", ")}`,
111
+ );
112
+ err.param = "size";
113
+ return sendOpenAIError(c, err);
114
+ }
115
+
116
+ const size =
117
+ requestedSize ?? (kind === "image" ? IMAGE_DEFAULT_SIZE : VIDEO_DEFAULT_SIZE);
118
+ const created = Math.floor(Date.now() / 1000);
119
+ const completionId = makeCompletionId();
120
+ const requestSignal = c.req.raw?.signal;
121
+ const startedAt = Date.now();
122
+
123
+ logMediaInfo(
124
+ mediaLog(kind, "request_started", {
125
+ operation: "chat.completions",
126
+ model,
127
+ prompt_chars: prompt.length,
128
+ size,
129
+ stream: isStream,
130
+ }),
131
+ );
132
+
133
+ const generate = async (): Promise<string> => {
134
+ if (kind === "image") {
135
+ const result = await generateImage({
136
+ prompt,
137
+ model,
138
+ size,
139
+ signal: requestSignal,
140
+ });
141
+ return `![Generated image](${result.url})`;
142
+ }
143
+ const result = await generateVideo({
144
+ prompt,
145
+ model,
146
+ size,
147
+ waitForCompletion: true,
148
+ signal: requestSignal,
149
+ });
150
+ if (result.status === "completed" && result.video_url) {
151
+ return formatGeneratedVideoContent(result.video_url);
152
+ }
153
+ throw new Error(
154
+ result.status === "failed"
155
+ ? "Video generation failed"
156
+ : "Video generation did not complete in time",
157
+ );
158
+ };
159
+
160
+ const promptTokens = estimatePromptTokens(prompt);
161
+ const usage = {
162
+ prompt_tokens: promptTokens,
163
+ completion_tokens: 0,
164
+ total_tokens: promptTokens,
165
+ };
166
+ const includeUsage = body.stream_options?.include_usage === true;
167
+
168
+ // ---- Non-streaming: return a complete chat.completion object ----
169
+ if (!isStream) {
170
+ try {
171
+ const content = await generate();
172
+ return c.json({
173
+ id: completionId,
174
+ object: "chat.completion",
175
+ created,
176
+ model,
177
+ choices: [
178
+ {
179
+ index: 0,
180
+ message: { role: "assistant", content },
181
+ finish_reason: "stop",
182
+ },
183
+ ],
184
+ usage,
185
+ });
186
+ } catch (error) {
187
+ logMediaError(
188
+ mediaLog(kind, "request_failed", {
189
+ operation: "chat.completions",
190
+ model,
191
+ stream: false,
192
+ duration_ms: Date.now() - startedAt,
193
+ error: error instanceof Error ? error.message : String(error),
194
+ }),
195
+ );
196
+ return sendOpenAIError(c, error, 500);
197
+ }
198
+ }
199
+
200
+ // ---- Streaming: role chunk, heartbeats while generating, then content ----
201
+ c.header("Content-Type", "text/event-stream");
202
+ c.header("Cache-Control", "no-cache");
203
+ c.header("Connection", "keep-alive");
204
+ c.header("X-Accel-Buffering", "no");
205
+
206
+ return honoStream(c, async (stream) => {
207
+ const encoder = new TextEncoder();
208
+ const writeChunk = async (payload: Record<string, unknown>) => {
209
+ await stream.write(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
210
+ };
211
+
212
+ const baseChunk = {
213
+ id: completionId,
214
+ object: "chat.completion.chunk",
215
+ created,
216
+ model,
217
+ };
218
+
219
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
220
+
221
+ try {
222
+ await writeChunk({
223
+ ...baseChunk,
224
+ choices: [
225
+ { index: 0, delta: { role: "assistant", content: "" }, finish_reason: null },
226
+ ],
227
+ });
228
+
229
+ // Generation can take up to ~120s (image) / ~300s (video). Keep the
230
+ // connection alive so clients do not time out while Qwen renders.
231
+ heartbeat = setInterval(() => {
232
+ stream.write(encoder.encode(": keep-alive\n\n")).catch(() => {});
233
+ }, STREAM_HEARTBEAT_MS);
234
+
235
+ let content: string;
236
+ try {
237
+ content = await generate();
238
+ } finally {
239
+ clearInterval(heartbeat);
240
+ }
241
+
242
+ await writeChunk({
243
+ ...baseChunk,
244
+ choices: [{ index: 0, delta: { content }, finish_reason: null }],
245
+ });
246
+ await writeChunk({
247
+ ...baseChunk,
248
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
249
+ ...(includeUsage ? { usage } : {}),
250
+ });
251
+ await stream.write(encoder.encode("data: [DONE]\n\n"));
252
+ } catch (error) {
253
+ if (heartbeat) clearInterval(heartbeat);
254
+ const message = error instanceof Error ? error.message : String(error);
255
+ logMediaError(
256
+ mediaLog(kind, "request_failed", {
257
+ operation: "chat.completions",
258
+ model,
259
+ stream: true,
260
+ duration_ms: Date.now() - startedAt,
261
+ error: message,
262
+ }),
263
+ );
264
+ try {
265
+ await writeChunk({
266
+ ...baseChunk,
267
+ choices: [
268
+ {
269
+ index: 0,
270
+ delta: { content: `⚠️ Media generation failed: ${message}` },
271
+ finish_reason: null,
272
+ },
273
+ ],
274
+ });
275
+ await writeChunk({
276
+ ...baseChunk,
277
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
278
+ });
279
+ await stream.write(encoder.encode("data: [DONE]\n\n"));
280
+ } catch {
281
+ // Client already disconnected; nothing else to do.
282
+ }
283
+ }
284
+ });
285
+ }